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);
bapap
  • 514
  • 8
  • 25
  • 2
    Possible duplicate of [Waiting for user to enter input in Node.js](https://stackoverflow.com/questions/18193953/waiting-for-user-to-enter-input-in-node-js) – tom Sep 05 '19 at 13:53

1 Answers1

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

Kay
  • 1,266
  • 10
  • 21
  • 1
    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. – bapap Sep 05 '19 at 14:23
  • Updated the answer to return the value and not console it. – Kay Sep 05 '19 at 14:30