joyent/node — Issue #2574: extend open to allow atomic fs operations?
Author: craigyk
Created: 2012-01-18 18:15:15+00:00
State: open

I'm trying to implement a file receiving server in node.js and I'm not sure how to deal with the possibility of dueling writes. If there is only one instance of the server running then it's easy, but if there is more than one instance, or I'm using workers to parallelize, than I can run into problems if say two processes try to write to the same file. I tested this by opening a file for write in two instances of the node REPL and was able to write to the same file, without any error, from both.

In python, I've handled this in the past, by passing the right flags to the system 'open' call. By using:
os.open(path, os.O_CREAT|os.O_EXCL|os.O_RDWR) I am able to exclusively create a new file in the FS in an atomic operation (I believe this call also works on windows?).

I propose, as a possibility, adding a 'c' flag to fs.open in node with this behavior to allow the atomic creation of new files, all other processes that lose in the race would return an error.