跳到内容

在 Node.js 中接受命令行输入

🌐 Accept input from the command line in Node.js

如何使 Node.js CLI 程序具有交互性?

🌐 How to make a Node.js CLI program interactive?

自 Node.js 7 版本起,提供了 readline 模块 来实现这一功能:从可读流(例如 process.stdin 流)获取输入。在 Node.js 程序执行期间,process.stdin 是终端输入,它可以按行读取数据。

🌐 Node.js since version 7 provides the readline module to perform exactly this: get input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time.

const  = ('node:readline');

const  = .({
  : .,
  : .,
});

.(`What's your name?`,  => {
  .(`Hi ${}!`);
  .();
});

这段代码会询问用户的名称,一旦输入文本并按下回车,我们就会发送一条问候信息。

🌐 This piece of code asks the user's name, and once the text is entered and the user presses enter, we send a greeting.

question() 方法显示第一个参数(一个问题)并等待用户输入。按下回车键后,它会调用回调函数。

🌐 The question() method shows the first parameter (a question) and waits for the user input. It calls the callback function once enter is pressed.

在此回调函数中,我们关闭 readline 接口。

🌐 In this callback function, we close the readline interface.

readline 提供了其他几种方法,请在上面链接的包文档中查看它们。

如果需要输入密码,最好不要将其回显,而是显示 * 符号。

🌐 If you need to require a password, it's best not to echo it back, but instead show a * symbol.