I'm trying to write to a fifo in my node.js server whenever a web request comes in. I'm using the fifo as a task queue, so that another program can read from it and do some time-consuming work.
So far I have code for my node.js server like this:
fs = require('fs');
...
var fifoPath = '/tmp/myfifo';
var input = 'some input';
fs.open(fifoPath, 'wx', 0644, function(error, fd) {
if (error) {
if (fd) {
fs.close(fd);
}
console.log('Error opening fifo: ' + error);
return;
}
fs.write(fd, input, 0, input.length, null, function(error, written, buffer) {
if (fd) {
fs.close(fd);
}
if (error) {
console.log('Error writing to fifo: ' + error);
} else {
if (written == input.length) {
console.log('Input has been written successfully!';
} else {
console.log('Error: Only wrote ' + written + ' out of ' + input.length + ' bytes to fifo.');
}
}
});
});
When this code runs, it outputs the following:
Error: EEXIST, open '/tmp/myfifo'
Am I doing this incorrectly?
Note: I'm using fs.open(...)
with 'wx'
flags to make sure the input get written to the fifo sequentially, e.g. when 10 requests come in at the same time, so they don't all write to the fifo at the same time.
'x'
doesn't do what you think. From the Node docs:
Exclusive mode (O_EXCL
) ensures that path is newly created. fs.open()
fails if a file by that name already exists.
What is the situation where you think exclusivity is needed? Nodejs is single-threaded, so it is never possible for two fs.write
calls to be interleaved, whichever comes up first will write first.