【发布时间】:2023-03-09 02:22:01
【问题描述】:
我正在使用 node.js 并通过打开 /dev/tty 文件从串行端口读取输入,我发送命令并读取命令的结果,并且我想在读取和解析后关闭流所有的数据。我知道我已经完成了数据标记的读取数据。我发现一旦我关闭了流,我的程序就不会终止。
以下是我所看到的示例,但使用 /dev/random 来缓慢生成数据(假设您的系统没有做太多事情)。我发现,一旦设备在流关闭后生成数据,进程就会终止。
var util = require('util'),
PassThrough = require('stream').PassThrough,
fs = require('fs');
// If the system is not doing enough to fill the entropy pool
// /dev/random will not return much data. Feed the entropy pool with :
// ssh <host> 'cat /dev/urandom' > /dev/urandom
var readStream = fs.createReadStream('/dev/random');
var pt = new PassThrough();
pt.on('data', function (data) {
console.log(data)
console.log('closing');
readStream.close(); //expect the process to terminate immediately
});
readStream.pipe(pt);
更新:1
我又回到了这个问题上,并且有另一个示例,这个示例只使用了一个 pty,并且很容易在节点 repl 中复制。在 2 个终端上登录,并在以下调用中使用您未运行节点的终端的 pty 来调用 createReadStream。
var fs = require('fs');
var rs = fs.createReadStream('/dev/pts/1'); // a pty that is allocated in another terminal by my user
//wait just a second, don't copy and paste everything at once
process.exit(0);
此时节点只会挂起而不退出。这是 10.28。
【问题讨论】:
-
也许这会有所帮助? stackoverflow.com/questions/16399476/…
-
我猜它没有帮助?万一您错过了,该问题的 OP 会将他们的解决方案放在问题的底部(至少对我来说,起初并不明显,它不仅仅是底部的更多问题)。
-
这是一种奇怪的行为。 OP 的代码在 Mac Os (node v0.10.21) 中立即退出...
-
可能我错过了,但通过关闭与他们的数据库(猫鼬)的连接解决了这个问题。除了代码中创建的流之外,我没有其他连接。
标签: node.js stream node.js-stream