我正在尝试使用readline从控制台捕获输入,但是我的代码没有等待输入。有人可以告诉我我在做什么错吗?该代码只是直截了当,并且不允许任何输入。
var readline = require('readline');
it('Input Check Number to Search for', function(){
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter Check Number: ", function(answer){
console.log("Answer = " + answer);
missingCheckNum = answer;
rl.close();
});
});
对我有用的解决方案:
it('Input Check Number to Search for', async function(){
const ans = await askQuestion("Enter missing check number ");
console.log("Missing check number is = " + ans);
missingCheckNum = ans;
});
function askQuestion(query) {
var readline = require('readline');
var rl = null;
rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
return new Promise(resolve => rl.question(query, ans => {
rl.close();
resolve(ans);
}))
}
答案 0 :(得分:0)
在您的代码中,rl.question
函数在其回调之前结束,因此rl
变量超出范围。在调用rl
函数之前(或全局调用),应定义it
var。