node.js - 在 Node.js 中暂停 readline

标签 node.js

考虑下面的代码......我试图在阅读前 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 the readline.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/

相关文章:

javascript - 解决 Node.js 中的 "Uncaught ReferenceError: require is not defined"错误

javascript - 当我推送 promise 数组时, promise 是否已解决?

javascript - socketIO url 中的 "?t="是什么

node.js - 如何更新 rethinkDB 中的嵌套对象

javascript - 如何在node.js中将动态创建的JSON对象转换为XML?

node.js - Node (内存泄漏,v8 快照)- 使用连接 promise 是不好的做法吗?

node.js - YouTube Data v3 API - 如何请求 channel 中的所有视频?

node.js - 如何使用 knex 查询 PostGresQl 检查逗号分隔字段中的单个值

node.js - MongoDB 未使用 graphql 在 Node js 中更新

javascript - 使用服务器js中的key从mongo获取数据