可靠地从NodeJS中的FIFO中读取 [英] Reliably reading from a FIFO in NodeJS

查看:223
本文介绍了可靠地从NodeJS中的FIFO中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个与第三方应用程序交互的NodeJS脚本.第三方应用程序将在打开期间将数据写入文件.我想让我的NodeJS应用程序实时接收这些数据.

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.

我的脚本创建了一个fifo:

My script creates a fifo:

child_process.spawnSync('mkfifo', [pipePath]);

然后使用child_process.spawn启动第三方应用程序.最后,它从管道读取.

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);
});

如果第3方应用程序正常运行,则效果很好.但是,在某些情况下,第三方应用程序将退出而无需写入文件/FIFO.在这种情况下,脚本中的fs.open()调用将永远被阻止. (请参阅GitHub上的此相关问题)

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);

如果第三方应用程序失败,这可以防止我的脚本挂起,但是即使第三方应用程序正常运行,现在也不会触发数据"事件.我想知道用O_NONBLOCK打开FIFO是否不算作已打开以供读取?

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?

我不确定解决此问题的最佳方法是什么.目前,我正在考虑启动第三方应用程序,等待10秒钟,看看它是否仍在运行,然后打开fifo进行读取,因为如果第三方应用程序完全失败了,它可能很快就会失败.但这是一个hack,所以我想知道什么是更好的解决方案.

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.

谢谢!

推荐答案

当然,我一问到这个问题就知道了.

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

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

这将打开fifo而不会阻塞,因为它同时连接了作者和读者.一个fifo可以有多个作者,因此第三方应用程序仍然可以连接而没有任何问题.

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.

这篇关于可靠地从NodeJS中的FIFO中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆