【问题标题】:Getting user's input in NodeJS "readline" module在 NodeJS“readline”模块中获取用户的输入
【发布时间】:2021-02-01 02:02:30
【问题描述】:

在 NodeJS 程序中,我想接受来自控制台的输入。我选择readline 来做这件事。代码可以简化如下:

const readline = require("readline"),
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });

function getInput() {
    rl.question("", (ans) => {
        console.log(ans);
    })
}

getInput();
rl.close();

但是每次我运行这个程序时,它都会在我输入之前退出。

我认为问题是由rl.close()语句引起的,它可能会在接受任何输入之前关闭界面。我怎样才能避免这种情况?

感谢您的回答!

【问题讨论】:

    标签: node.js readline


    【解决方案1】:

    getInput 包装成这样的承诺:

    function getInput() {
        return new Promise(function (resolve, reject) {
            rl.question("what's your option? ", (ans) => {
                console.log(ans);
                resolve(ans);
            });
        });
    }
    
    // and await here
    
    await getInput();
    rl.close();
    
    

    【讨论】:

    • 不,它不起作用。 sais await 只能在异步函数中使用:await getInput(); ^^^^^ SyntaxError: await is only valid in async function
    • 这是一个不同的问题,但您可以将其包装在这样的异步方法中。 (async()=>{ await getInput(); rl.close(); })();
    • 如果您对 await 语法不满意,也可以使用旧的回调方式 getInput().then(()=>{rl.close();})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多