1

I have a code that gets input but it does not work. I want the code to wait while input is not completed. I don't want to install any packages because when someone only takes the code, it needs to work.

I use NodeJS for code.

My code:

const readline = require('readline');

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

    let complete = false;

    rl.question(prompt, (answer) => {
        complete = true;

        return answer;

        rl.close();
    });

    while (!complete) {}
}

number = input("Number: ");

console.log(number);
1

1 Answer 1

2

Try out this snippet:

async function question(){
    const readline = require('readline');

    const input = async prompt => {
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        return new Promise(resolve => rl.question(prompt, answer => {
            rl.close();
            resolve(answer);
        }))
    }

    return await input("Number: ");
}

Call the function as await question()

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

2 Comments

Thank you! It worked for me, but i don't want to print the input, i want to return the input and i want to do something with it.
Updated the answer to return the value and not console it.

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.