如何在Node.js中使用readline将所有input行都放入数组中?
我想创build一个方便的函数,为CodeAbbey的目的做这样的事情:
var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var lines = []; rl.on('line', (line) => { lines.push(line); }); return lines;
但是,由于readline
作为一个事件处理程序的function,当然我只能返回一个空数组。
如何在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
中的许多Readline
都是asynchronous的。 一般来说,当发生close
事件时,您将需要处理lines
。
你可能会发现这个非常类似的解决问题有帮助: node.js:读取文本文件到数组中。 (每行在数组中的一个项目。)
希望这可以帮助!
您将要在close事件中访问lines数组:
var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var lines = []; rl.on('line', (line) => { lines.push(line); }); rl.on('close', () => { console.log(lines); });
这段代码将build立createInterface,并初始化一个空的数组lines
。 在提示符下,当用户点击回车键时,它会触发“行”事件,并将之前写入的行添加到行数组中。 closures界面时(通过杀死进程或手动closures代码)将会注销arrays。
$ node readlines.js this is the second line third [ 'this is', 'the second line', 'third' ]