Search code examples
javascriptnode.jsreadline

Why does only one Node readline object work?


In the following node.js example I want to ask the user for two numbers and then return the sum back to the console. I have used readline.question() twice (one for each number) but the user is asked only for the second number. Why does the first console prompt not appear?

const readline = require('readline');

let firstNumber = 0;
let secondNumber = 0;

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

rl.question('Your first number: ', (answer) => {
    firstNumber = parseInt(answer);
    rl.close();
});

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

r2.question('Your second number: ', (answer) => {
    secondNumber = parseInt(answer);
    console.log(`The sum of these numbers is: ${secondNumber + firstNumber}`);
    r2.close();
});

Solution

  • If you want to wait for the first question to get answered, you need to ask the second one after the answer comes back, like this:

    const readline = require('readline');
    
    let firstNumber = 0;
    let secondNumber = 0;
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Your first number: ', (answer) => {
        firstNumber = parseInt(answer);
        rl.question('Your second number: ', (answer) => {
            secondNumber = parseInt(answer);
            console.log(`The sum of these numbers is: ${secondNumber + firstNumber}`);
            rl.close();
        });
    });
    

    Functions that take time in javascript are scheduled and the interpreter continues.

    If you want something to happen after something else, you need to do it in a callback or promise.then mechanism.

    You'll get the hang of it.