Node.js - MaxListenersExceededWarning - 使用 readline 模块编写 Node.js CLI 应用程序时
Node.js - MaxListenersExceededWarning - when writing a Node.js CLI application uisng readline module
我正在尝试在循环中继续添加数字,如下面的代码所示:
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;
}
})();
但是这里有两个问题:
- 如屏幕截图所示,它多次打印单个按键。
- 循环几次后,报错如下:
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
公开了一个 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();
});
我正在尝试在循环中继续添加数字,如下面的代码所示:
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;
}
})();
但是这里有两个问题:
- 如屏幕截图所示,它多次打印单个按键。
- 循环几次后,报错如下:
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
公开了一个 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();
});