Node.js で無限に readline を実行する方法 質問する

Node.js で無限に readline を実行する方法 質問する
while(1){
    rl.question("Command: ",function(answer){
    console.log(answer);
    })
}

このコードを試してみましたが、入力が 1 つずつ取得されるのではなく、「コマンド:」行が点滅します。node.js が非ブロッキングであることはわかっていますが、この問題を解決する方法がわかりません。

ベストアンサー1

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

重要なのは、同期ループを使用しないことです。rl.question答えを処理した後でのみ、次の質問をする必要があります。再帰が正しい方法です。質問をして答えを処理する関数を定義し、答えの処理後にその関数を内部から呼び出します。この方法では、通常のループと同じように最初からやり直します。ただし、ループは非同期コードを気にしませんが、実装では気にします。

おすすめ記事