我正在 MEAN 堆栈中编程,所以我有我的 app.js,并且我想构建一个进程,该进程将从其运行的 shell 中获取命令 (process.stdin)
目前我已经尝试过:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
});
但它会将我的输入写入两次并在 1 行后退出。
我需要一个 readline 函数,它将循环并从我这里获取无限命令。
我怎么才能得到它 ?
最佳答案
它退出的原因是:
rl.close();
如果您想使用 readline 交互式地逐行读取:
rl.on('line', (line) => {
// use line here
});
另一种方法对于交互性较低的工作流程可能很方便,但仍然适用于交互性:
const filt = require('filt');
filt((line) => {
// use line here
});
第二个示例使用 filt
模块(免责声明:我是该模块的作者)。
关于javascript - 在 Node.js 中写入 process.stdin 并解析该行的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975249/