在 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 程序执行期间,它是终端输入,一次一行。
¥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 readline = require('node:readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(`What's your name?`, name => {
console.log(`Hi ${name}!`);
rl.close();
});
这段代码询问用户的名称,一旦输入文本并且用户按下回车键,我们就会发送问候语。
¥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()
方法显示第一个参数(一个问题)并等待用户输入。按下 Enter 后,它会调用回调函数。
¥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
提供了其他几种方法,请在上面链接的软件包文档中查看它们。
¥readline
offers several other methods, please check them out on the package documentation linked above.
如果你需要输入密码,最好不要回显密码,而是显示 *
符号。
¥If you need to require a password, it's best not to echo it back, but instead show a *
symbol.
最简单的方法是使用 readline-sync
包,它在 API 方面非常相似,并且可以开箱即用。
¥The simplest way is to use the readline-sync
package which is very similar in terms of the API and handles this out of the box.
Inquirer.js 包 提供了一个更完整、更抽象的解决方案。
¥A more complete and abstract solution is provided by the Inquirer.js package.
你可以使用 npm install inquirer
安装它,然后你可以像这样复制上述代码:
¥You can install it using npm install inquirer
, and then you can replicate the above code like this:
const inquirer = require('inquirer');
const questions = [
{
type: 'input',
name: 'name',
message: "What's your name?",
},
];
inquirer.prompt(questions).then(answers => {
console.log(`Hi ${answers.name}!`);
});
Inquirer.js 可让你执行许多操作,例如询问多项选择、单选按钮、确认等。
¥Inquirer.js lets you do many things like asking multiple choices, having radio buttons, confirmations, and more.
值得了解所有替代方案,尤其是 Node.js 提供的内置替代方案,但如果你计划将 CLI 输入提升到一个新的水平,Inquirer.js 是最佳选择。
¥It's worth knowing all the alternatives, especially the built-in ones provided by Node.js, but if you plan to take CLI input to the next level, Inquirer.js is an optimal choice.