Skip to content
Advertisement

readline not pausing for or allowing input

Here is my code:

readline = require("readline");
input = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
while (true) {
    input.question("What do you want me to do?", answer => {
        console.log("1");
        //do stuff with answer
        input.close();
    });
    console.log("2");
}

(The console.log()s are just so I can see what code is evaluated and which isn’t) This just returns What do you want me to do?2 over and over again. It also doesn’t let me type anything in to the console.

How can I fix this? I’ve looked all over and haven’t found anything.

Advertisement

Answer

while (true) will indeed create an infinite loop (unless you break it). And input.question() takes a callback function as a parameter, which gets executed only when you submit your answer. It’s asynchronous. While it’s waiting for your answer, your loop keeps running over and over.

I’m guessing you want to wait for an answer before running your loop again. You can do this by wrapping that code with a function, and calling that function from inside the callback.

The following example will loop if you type ask me again as an answer. It will stop otherwise:

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

(function loop() {
  input.question("What do you want me to do?", (answer) => {
    const askAgain = answer === "ask me again";

    if (askAgain) loop();
    else input.close();
  });
})();

Note the way it’s wrapped with (function loop() {})();. That’s an IIFE (Immediately Invoked Function Expression). It’s equivalent to doing this:

function loop() {}
loop();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement