Search code examples
node.jsreadline

Getting user's input in NodeJS "readline" module


In a NodeJS program, I want to accept input from console. I chose readline to do this. The code can be simplified as follow:

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

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

getInput();
rl.close();

But every time I run this program, it exits before I could make any input.

I think the problem is caused by the statement rl.close(), it may close the interface before accepting any input. How can I avoid this?

Thanks for answering!


Solution

  • Wrap the getInput in a promise like this:

    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();