【问题标题】:Node.js - MaxListenersExceededWarning - when writing a Node.js CLI application uisng readline moduleNode.js - MaxListenersExceededWarning - 使用 readline 模块编写 Node.js CLI 应用程序时
【发布时间】:2022-01-01 17:44:28
【问题描述】:

我正在尝试在循环中不断添加数字,如下面的代码所示:

const readline = require('readline');

const askOnCommandLine = (question) =>
  new Promise((resolve) => {
    const p = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      prompt: question,
    });

    p.on('line', (input) => {
      resolve(input);
    });

    p.prompt();
  });

let counter = 0;

(async () => {
  while (true) {
    console.log('Loop:', counter);
    const number1 = await askOnCommandLine('Enter 1st number: ');
    const number2 = await askOnCommandLine('Enter 2nd number: ');
    console.log('Addition:', parseInt(number1) + parseInt(number2));
    counter += 1;
  }
})();

但是这里有两个问题:

  1. 它会多次打印单个按键,如屏幕截图所示。

  1. 循环几次后,出现如下错误:
Enter 2nd number:
(node:706492) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
11 end listeners added to [ReadStream]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)

【问题讨论】:

  • 您多次调用readline.createInterface() 却没有完成之前的调用。 p.close() 将关闭前一个,因此您可以在同一流上打开多个。但是,实际上,您通常不会在每次想问下一个问题时都创建一个新界面。这就是 rl.prompt()rl.question() 的用途。

标签: node.js command-line-interface readline nodejs-stream


【解决方案1】:

就像浏览器中的事件侦听器一样,在处理完这些流接口后,您需要处理它们,否则它们只会在内存中不断累积(因此会出现警告和意外行为)。看起来readline 公开了一个close() 方法,为什么不在完成后关闭流?

const askOnCommandLine = (question) =>
  new Promise((resolve) => {
    const p = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      prompt: question,
    });

    p.on('line', (input) => {
      resolve(input);
      p.close();
    });

    p.prompt();
  });

【讨论】:

  • 阅读完文档后,我正要回答我自己的问题。但是你已经做到了。这是公认的答案。另外,我已经从 p.on 切换到 p.question。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 2012-09-20
相关资源
最近更新 更多