在 NodeJS "readline" 模块中获取用户的输入

Getting user's input in NodeJS "readline" module

在 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(),它可能会在接受任何输入之前关闭界面。我怎样才能避免这种情况?

感谢您的回答!

用这样的承诺包装 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();