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

标签 javascript node.js asynchronous 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

关于javascript - 如何在 Node.js 中使用 readline 模块时添加异步行读取之间的间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37709832/

相关文章:

node.js - 如何测试通过模拟从 express 调用的路由处理程序

node.js - 全局安装本地开发的 npm 包

json - 测试用例 : SwiftHTTP library not making the HTTP call

javascript - 如何使用单击事件处理程序在点之间画线?

javascript - 服务器响应 404。ajax 调用未到达 Controller

javascript - 如何判断脚本当前是否处于事件状态?

javascript - 乘以 100 后的值错误

node.js - sails.js 中的多个数据库连接,每个连接具有迁移设置

javascript - 是否可以在没有 return 关键字的情况下解析异步函数

PHP:立即返回响应,但在后台运行多个冗长的 shell_exec 函数