node.js - 如何关闭没有更多数据可在 node.js 中发送的流?

标签 node.js stream node.js-stream

我正在使用 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 并且很容易在 Node repl 中重现。在 2 个终端上登录并在以下调用 createReadStream 时使用您未运行 Node 的终端的 pty。

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

此时 Node 将挂起而不退出。这是 10 月 28 日。

最佳答案

而不是使用

readStream.close(), 

尝试使用

readStream.pause().

但是,如果您使用的是最新版本的 Node ,请使用从 stream 创建的对象包装读取流isaacs 的模块,像这样:

var Readable = require('stream').Readable;
var myReader = new Readable().wrap(readStream);

然后使用 myReader 代替 readStream。

祝你好运!告诉我这是否有效。

关于node.js - 如何关闭没有更多数据可在 node.js 中发送的流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19979529/

相关文章:

node.js - 如何杀死重生 Node

javascript - Promise 通过 for 循环提前返回

.net - .NET Streams 是否节省内存?

string - Node.js - 如何将流转换为字符串

javascript - 两个 Node 服务器是否可以同时运行并交互,以便一个作为客户端服务的中介?

javascript - 给定数字而不是数组的功能循环

android - MediaPlayer,只有视频 m3u8 HTML 流工作

ios - QuickTime Player(或实际上是 CoreMedia)在播放 HTTP 流时如何工作?

node.js - 如何等待所有 Node 流完成/结束?