在 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.