我想创建一个方便的函数来为 CodeAbbey 做这样的事情:
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var lines = [];
rl.on('line', (line) => {
lines.push(line);
});
return lines;
但是,由于 readline
如何充当事件处理程序,当然我得到的只是一个空数组。
如何让 readline 在这里执行所需的行为?还是我使用其他图书馆?我宁愿只使用“默认”组件,但如果我必须使用其他组件,我会使用。
最佳答案
var lines = [];
rl.on('line', (line) => {
lines.push(line);
}).on('close', () => {
// Do what you need to do with lines here
process.exit(0);
});
由于 Node.js
在事件循环上运行,许多包中可用的许多功能(包括 Readline
)都是异步的。通常,您需要在 close
事件发出时处理 lines
。
您可能会发现这个非常相似的已解决问题很有帮助: node.js: read a text file into an array. (Each line an item in the array.)
希望这对您有所帮助!
关于javascript - 如何在 Node.js 中使用 readline 将所有输入行放入数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475755/