I'm writing a NodeJS script which interacts with a 3rd party application. The third party application will write data to a file for the duration that it's open. I'd like for my NodeJS application to receive this data in real-time.
My script creates a fifo:
child_process.spawnSync('mkfifo', [pipePath]);
It then launches the 3rd party application using child_process.spawn
. Finally, it reads from the pipe.
let pipeHandle = await promisify(fs.open)(pipePath, fs.constants.O_RDONLY);
let stream = fs.createReadStream(null, {fd: pipeHandle, autoClose: false});
stream.on('data', d => {
console.log(d.length);
});
This works great if the 3rd party application works. However, under certain circumstances the 3rd party application will exit without ever writing to the file/FIFO. In this case, the fs.open() call in my script blocks forever. (See this related issue on GitHub)
In an attempt to fix this, I used
let pipeHandle = await promisify(fs.open)(pipePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
This prevents my script from hanging if the 3rd party app fails, but now the 'data' event never gets fired, even when the 3rd party app works correctly. I'm wondering if opening a FIFO with O_NONBLOCK doesn't count as having it open for reading?
I'm not sure what the best way to resolve this is. At the moment I'm considering launching the 3rd party app, waiting for 10 seconds, seeing if it's still running and THEN opening the fifo for reading, as the third party app is likely to fail quickly if it's going to fail at all. But this is a hack, so I'm wondering what the better solution is.
Thanks!