1

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!

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

No, it doesn't work. It sais await can only be used in async functions: await getInput(); ^^^^^ SyntaxError: await is only valid in async function
that's a different question but you can wrap it in an async method like this. (async()=>{ await getInput(); rl.close(); })();
Or the old call back way getInput().then(()=>{rl.close();}) if you are not comfortable with the await sytax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.