暂停Node.js中的readline [英] Pausing readline in Node.js

查看:322
本文介绍了暂停Node.js中的readline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码...阅读前5行后,我试图暂停流:

Consider the code below ... I am trying to pause the stream after reading the first 5 lines:

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在缓冲区中排队了几行,并且无论如何都将它们喂给我...如果它继续在后台异步读取,这是有道理的,但是根据文档,我不知道该怎么做.应有适当的行为.关于如何达到预期效果有什么建议吗?

The output (copied next) suggests that it keeps reading lines after the pause. Perhaps readline has queued up a few more lines in the buffer, and is feeding them to me anyway ... this would make sense if it continues to read asynchronously in the background, but based on the documentation, I don't know what the proper behavior should be. Any recommendations on how to achieve the desired effect?

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

推荐答案

因此,事实证明,即使在pause()之后,readline流也趋向于滴落"(即,泄漏了一些额外的行).该文档没有明确说明,但这是事实.

So, it turns out that the readline stream tends to "drip" (i.e., leak a few extra lines) even after a pause(). The documentation does not make this clear, but it's true.

如果要使pause()切换立即显示,则必须创建自己的行缓冲区并自己累积剩余的行.

If you want the pause() toggle to appear immediate, you'll have to create your own line buffer and accumulate the leftover lines yourself.

这篇关于暂停Node.js中的readline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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