有没有办法在 Node.js 中暂停带有 process.stdin 的 运行 脚本供用户输入?

Is there a way to pause a running script with process.stdin for user input in Node.js?

我希望看看 Node.js 是否能够在脚本遇到 process.stdin 块时暂停脚本以接收命令行应用程序的用户输入,类似于 [=26] =]prompt() 在浏览器中与 JS 一起工作,或者 gets 如何在 Ruby.

中工作
  var response = '';

  console.log("What's your favorite color?");

  process.stdin.resume();
  process.stdin.setEncoding('utf8');

  process.stdin.on('data', function (text) {
    response = text;
    process.exit();
  });

  console.log(`Cool! So ${response} is your favorite color? Mine is black.`);

在上面的简单脚本中,我希望看到

What's your favorite color?
*pause for user input ===>* Red
Cool! So Red is your favorite color? Mine is black.

暂停会停止脚本,直到我输入内容并按回车键以继续 运行。相反,我看到

What's your favorite color?
Cool! So  is your favorite color? Mine is black.

立即打印出来,然后接受我的用户输入。

我知道还有其他模块,如 readlineprompt 可以简化节点的用户输入。对于这个问题,我特别想看看 Node.js 是否提供此功能而无需安装额外的软件包(process.stdin 是首先想到的),尽管了解是否会有所帮助任何模块也提供这种功能。

在继续您的脚本之前等待标准输入

  var response = '';

  console.log("What's your favorite color?");

  process.stdin.resume();
  process.stdin.setEncoding('utf8');

  process.stdin.on('data', function (text) {
    response = text;
    console.log(`Cool! So ${response} is your favorite color? Mine is black.`);
    process.exit();
  });

您可以使用 readline-sync.

var rl = require('readline-sync');
var response = '';

response = rl.question("What's your favorite color?");

console.log(`Cool! So ${response} is your favorite color? Mine is black.`);