var readline = require('readline');
var reader = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
function stdinput(){
reader.on('line', function (cmd) {
return cmd;
});
}
console.log(stdinput());
输出:
undefined
stdinput() 函数在从 stdin 读取输入之前给出“未定义”。 我搜索了很多资源,但无法理解为什么它是异步解释的。
I am writing CLI interactive application in nodejs. it reads input many times. If we use recursion to read, it takes more stack memory and If we use callbacks, Promise and Async/await here also getting undefined before stdinput() i.e below part of the code is executing first before reading input.
最佳答案
或者您可以使用回调:
var readline = require('readline');
var reader = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
function stdinput(callback){
reader.on('line', function (cmd) {
callback (cmd);
});
}
stdinput(function (cmd) {
console.log('cmd: ', cmd);
});
关于javascript - 如何使用nodejs readline库通过返回函数从stdin读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722923/