问题描述
我刚刚开始使用Node.js,但我不知道如何获取用户输入.我正在寻找python函数 input()
或C函数 gets
的JavaScript对应版本.谢谢.
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function input()
or the C function gets
. Thanks.
推荐答案
您可以使用 readline
或 prompt
,所以我将向您介绍两个示例...
You could use readline
or prompt
, so I will walk you through both examples...
readline
是Node.js中的内置模块.您只需要运行以下代码:
readline
is a built-in module in Node.js. You only need to run the code below:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name ? ", function(name) {
rl.question("Where do you live ? ", function(country) {
console.log(`${name}, is a citizen of ${country}`);
rl.close();
});
});
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});
如果所有这些听起来都很复杂,请查看提示
示例.
If all of this sounds complicated, please have a look at prompt
example.
提示
是npm上可用的模块:
prompt
is a module available on npm:
运行命令 npm install提示符
来安装软件包,然后复制/粘贴以下代码:
Run the command npm install prompt
to install the package, and then copy/paste the following code:
const prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
if (err) { return onErr(err); }
console.log('Command-line input received:');
console.log(' Username: ' + result.username);
console.log(' Email: ' + result.email);
});
function onErr(err) {
console.log(err);
return 1;
}
享受!
这篇关于通过Node.js控制台获取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!