如何在Node.js中无限读取

while(1){
    rl.question("Command: ",function(answer){
    console.log(answer);
    })
}

刚刚尝试了这段代码,但是逐个输入,它会使“Command:”行闪烁.我知道node.js是非阻塞的,但我不知道如何解决这个问题.

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

关键是不要使用同步循环.我们应该在处理答案后才问下一个问题.递归是要走的路.我们定义函数,询问问题并处理答案,然后在答案处理后从内部调用它.这种方式我们从头开始,就像常规循环一样.但循环不关心ansyc代码,而我们的实现关心.

翻译自:https://stackoverflow.com/questions/24464404/how-to-readline-infinitely-in-node-js