【问题标题】:How to add interval between async line reads while using readline module in Node.js如何在 Node.js 中使用 readline 模块时添加异步行读取之间的间隔
【发布时间】:2016-06-08 18:08:18
【问题描述】:

我可以像这样在 Node.js 中逐行流式传输文件:

var rd = readline.createInterface({
  input: fs.createReadStream('/path/to/file'),
  output: process.stdout,
  terminal: false
});

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

有没有办法在每个console.log() 调用之间添加一个间隔,同时使整个过程异步?

意味着从程序的任何其他部分产生的任何日志语句都会与来自 readline 的语句混合在控制台上发布

我的服务器正在侦听需要发布的传入消息。当他们进来时,直到readline 读取整个文件之后才会发布。

【问题讨论】:

  • 你想要完成什么?也许有另一种方法。
  • 它的要点是我正在生成两种消息。一个来自静态日志文件,另一个来自客户端。对于文件,我只是使用 readline 遍历文件中的每一行。但是这个文件可能非常大,因此来自客户端的任何传入消息也需要在它们到来时发布。当来自客户端的消息进入时,我想暂停文件中的 readline,然后在发布客户端消息时从同一位置恢复。可以对传入消息进行暂停,但是如何判断该消息已在控制台上发布。
  • 对不起,如果我有更复杂的事情:)
  • 你想限制控制台日志?
  • 对于 readline 输出,是的。但也让它非阻塞

标签: javascript node.js asynchronous readline


【解决方案1】:

每条消息仅在 1 秒间隔内处理

// debounce function - await fn call with timeout
// credits: https://remysharp.com/2010/07/21/throttling-function-calls
function debounce(fn, delay) {
  var timer = null;
  return function() {
    var context = this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  };
}
rd.on('line', debounce(function(line) {
  console.log(line);
}, 1000)); // <== call fn only within 1sec

伪输出:

1sec:
  line: some text
  log: some text

2sec:
  line: another text
  log: another text

2.5sec:
  line: quick message text

2.9sec:
  line: dota 2 manila major   

3sec:
  log: quick message text
  log: dota 2 manila major

【讨论】:

    猜你喜欢
    • 2012-12-04
    • 1970-01-01
    • 2020-06-13
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多