Reliably reading from a FIFO in NodeJS

无人久伴 提交于 2019-12-02 07:37:28

问题


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!


回答1:


Of course I figure it out as soon as I ask the question.

let pipeHandle = await promisify(fs.open)(pipePath, fs.constants.O_RDWR);

This opens the fifo without blocking, because it connects a writer and a reader at the same time. There can be multiple writers for a fifo, so the 3rd-party app is still able to connect without any issues.



来源:https://stackoverflow.com/questions/53492401/reliably-reading-from-a-fifo-in-nodejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!