How to readline infinitely in Node.js

user2477 picture user2477 · Jun 28, 2014 · Viewed 19.4k times · Source
while(1){
    rl.question("Command: ",function(answer){
    console.log(answer);
    })
}

Just tried this code, but instead get input one by one, it blink the "Command: " line. I know node.js is non-blocking but i don't know how to fix this problems.

Answer

mynameisdaniil picture mynameisdaniil · Jun 28, 2014
var readline = require('readline');
var log = console.log;

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

var recursiveAsyncReadLine = function () {
  rl.question('Command: ', function (answer) {
    if (answer == 'exit') //we need some base case, for recursion
      return rl.close(); //closing RL and returning from function.
    log('Got it! Your answer was: "', answer, '"');
    recursiveAsyncReadLine(); //Calling this function again to ask new question
  });
};

recursiveAsyncReadLine(); //we have to actually start our recursion somehow

The key is to not to use synchronous loops. We should ask next rl.question only after handling answer. Recursion is the way to go. We define function that asks the question and handles the answer and then call it from inside itself after answer handling. This way we starting all over, just like with regular loop. But loops don't care about ansyc code, while our implementation cares.