我正在尝试从人偶项目中的CLI获取用户名和密码。我想问一个问题,可以很好地使用该值,但是当我执行第二个问题时,它只会冻结输入。几乎就像它实际上没有关闭并返回一样。我似乎无法弄清楚我所缺少的。我试图在问题方法中声明该接口,然后在调用close时销毁它,但这没有用。我感觉自己已经接近了,但是我无法弄清自己想念的是什么。
const login = require('../common/login.js');
userId = await login.getUserId();
console.log(userId) //works
password = await login.getPassword();
console.log(password) //does not work
login.js
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
var methods = {};
const question = (promptText) => {
let response;
readline.setPrompt(promptText)
readline.prompt();
return new Promise((resolve, reject) => {
readline.on('line', (userInput) => {
console.log('hi');
response = userInput;
readline.close();
});
readline.on('close', () => {
console.log('bye');
resolve(response);
})
})
};
methods.getUserId = async() => {
let username = question("Username: ");
return username;
}
methods.getPassword = async() => {
let password = question("Password: ");
console.log(password);
return password;
}
module.exports = methods;
答案 0 :(得分:0)
readline.close()
将关闭流。下面的代码对我有用
function input(prompt) {
return new Promise((callbackFn, errorFn) => {
readline.question(prompt, (uinput)=> {
callbackFn(uinput);
}, ()=> {
errorFn();
});
});
}
const main = async () => {
amt = await input("Enter the amount to check: ");
doSomething(amt);
uname = await input("Enter your name: ");
doSomethingElse(uname);
rli.close();
};
main();