Javascript 同步控制台提示

Javascript Synchronous Console Prompt

我正尝试通过在控制台上制作井字游戏来开始 Javascript。这将需要一个 while 循环来接收用户的移动。

事实证明,这比我预期的要难得多。有没有我想念的简单方法。

我试过使用 async.whilst 和同步提示。前者只是让我陷入无限循环,而后者在我尝试使用 npm install 下载它时出现错误。感谢您提供的任何帮助!

您不需要使用图书馆。只需使用节点的内置 readline.

这是他们的例子:

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log('Thank you for your valuable feedback:', answer);

  rl.close();
});

我找到了这个prompt-sync. It's not the same as the one you tried. In any case, if for some reason the npm installation fails, you can always grab the source code from its github page

虽然这不是一个完美的解决方案,至少对我来说是这样,因为它不会捕捉答案中的重音字符或西班牙语 ñ 字符。

无论如何,这在节点上似乎不是一件容易的事。

更新:我找到了另一种有效的方法,至少对我来说是这样,从节点 8 开始,通过使用 async 和 await 结合 IIFE:

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

    function prompt(message) {
        return new Promise((resolve, reject) => {
            rl.question(message, (answer) => {
                resolve(answer);
            });
        }); 
    }  

    var answer = await prompt("What do you have to say? ");
    console.log("\nYou answered: \n" + answer);
    rl.close(); 
})();