我試圖繼續在回圈中添加數字,如下面的代碼所示:
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)
uj5u.com熱心網友回復:
就像瀏覽器中的事件偵聽器一樣,您需要在處理完這些流介面后處理它們,否則它們只會在記憶體中不斷積累(因此會出現警告和意外行為)。看起來像是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();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/400235.html
標籤:节点.js 命令行界面 阅读线 nodejs-stream
