Node.js Readline 接口“暂停"事件不会暂停输入流 [英] Node.js Readline Interface 'pause' event does not pause input stream

查看:37
本文介绍了Node.js Readline 接口“暂停"事件不会暂停输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望下面的代码创建一个 Readline 接口,其中包含一个包含 ~1000 个 URL 列表的文件中的可读流,从输入流开始流式传输(将一行记录到控制台),然后暂停:

I expect the code below to create a Readline Interface with a readable stream from a file with a list of ~1000 URLs, start streaming from the input stream (logging a line to the console), and then pause:

var readline = require('readline');
var fs = require('fs');

var rlinterface = readline.createInterface({
    input: fs.createReadStream('urls.txt'),
    output: null,
    terminal: false
});

rlinterface.on('pause', function() {
    console.log('Readline paused.');
});

rlinterface.on('line', function(line){
    console.log(line);
    rlinterface.pause();
}); 

pause 事件的侦听器通知我应该暂停流,但是来自输入流的文件中的所有行都记录到控制台,表明流从未暂停.即使流没有在第一行之后立即暂停(可能需要额外的几行 在缓冲区中捕获),我不希望来自输入流的文件中的所有行都在暂停"之前流式传输.怎么回事?

The listener for the pause event notifies me that the stream should be paused, but all of the lines in the file from the input stream are logged to the console, suggesting that the stream never paused. Even if the stream doesn't pause immediately after the first line (maybe a few extra lines need to be captured in a buffer), I don't expect all of the lines from the file from the input stream to be streamed before the 'pause'. So what's going on?

推荐答案

可能发生的情况是整个文件都被一次读入,当你 pause() 时,什么都没有了阅读.具体来说,fs.ReadStream 的默认 highWaterMark64KB,因此可读流可以在第一次读取时轻松消耗您的整个 17KB 文件,因为它试图将内部缓冲区保持满 highWaterMark.

What's probably happening is that the entire file is being read in at once and by the time you pause(), there's nothing left to read. Specifically, the default highWaterMark for fs.ReadStream is 64KB, so the Readable stream could easily consume your entire 17KB file in the first read because it tries to keep the internal buffer full up to highWaterMark.

这篇关于Node.js Readline 接口“暂停"事件不会暂停输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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