如何在 Node.js 中使用 readline 模块时添加异步行读取之间的间隔



我可以在 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读取整个文件后才会发布。

每条消息仅以 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

最新更新