考虑下面的代码......我试图在阅读前 5 行后暂停流:
var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
var numlines = 0;
var instream = fs.createReadStream("myfile.json");
var outstream = new stream;
var readStream = readline.createInterface(instream, outstream);
readStream.on('line', function(line){
numlines++;
console.log("Read " + numlines + " lines");
if (numlines >= 5) {
console.log("Pausing stream");
readStream.pause();
}
});
输出(下一个复制)表明它在暂停后继续读取行。也许 readline 已经在缓冲区中排队了几行,并且无论如何都将它们提供给我......如果它继续在后台异步读取这将是有意义的,但根据文档,我不知道是什么应有的行为。关于如何达到预期效果有什么建议吗?
Read 1 lines
Read 2 lines
Read 3 lines
Read 4 lines
Read 5 lines
Pausing stream
Read 6 lines
Pausing stream
Read 7 lines
最佳答案
有点不直观,the pause methods does not stop queued up line events :
Calling
rl.pause()
does not immediately pause other events (including'line'
) from being emitted by thereadline.Interface
instance.
但是有一个名为 line-by-line
的第三方模块pause
does 暂停 line
事件直到它恢复为止。
var LineByLineReader = require('line-by-line'), lr = new LineByLineReader('big_file.txt'); lr.on('error', function (err) { // 'err' contains error object }); lr.on('line', function (line) { // pause emitting of lines... lr.pause(); // ...do your asynchronous line processing.. setTimeout(function () { // ...and continue emitting lines. lr.resume(); }, 100); }); lr.on('end', function () { // All lines are read, file is closed now. });
(我与该模块无关,只是发现它对处理这个问题很有用。)
关于node.js - 在 Node.js 中暂停 readline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21341050/