Node.js 中的用户输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17837147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User input in Node.js
提问by vamosrafa
I am writing a program which will create an array of numbers, and double the content of each array, and storing the result as key/value pair. Earlier, I had hardcoded the array, so everything was fine.
我正在编写一个程序,它将创建一个数字数组,并将每个数组的内容加倍,并将结果存储为键/值对。早些时候,我对数组进行了硬编码,所以一切都很好。
Now, I have changed the logic a bit, I want to take the input from users and then, store the value in an array.
现在,我稍微改变了逻辑,我想从用户那里获取输入,然后将值存储在一个数组中。
My problem is that I am not able to figure out, how to do this using node.js. I have installed the prompt module using npm install prompt, and also, have gone through the documentation, but nothing is working.
我的问题是我无法弄清楚如何使用 node.js 来做到这一点。我已经使用 npm install prompt 安装了 prompt 模块,并且已经阅读了文档,但没有任何效果。
I know that I am making a small mistake here.
我知道我在这里犯了一个小错误。
Here's my code:
这是我的代码:
//Javascript program to read the content of array of numbers
//Double each element
//Storing the value in an object as key/value pair.
//var Num=[2,10,30,50,100]; //Array initialization
var Num = new Array();
var i;
var obj = {}; //Object initialization
function my_arr(N) { return N;} //Reads the contents of array
function doubling(N_doubled) //Doubles the content of array
{
doubled_number = my_arr(N_doubled);
return doubled_number * 2;
}
//outside function call
var prompt = require('prompt');
prompt.start();
while(i!== "QUIT")
{
i = require('prompt');
Num.push(i);
}
console.log(Num);
for(var i=0; i< Num.length; i++)
{
var original_value = my_arr(Num[i]); //storing the original values of array
var doubled_value = doubling(Num[i]); //storing the content multiplied by two
obj[original_value] = doubled_value; //object mapping
}
console.log(obj); //printing the final result as key/value pair
Kindly help me in this, Thanks.
请在这方面帮助我,谢谢。
采纳答案by josh3736
Prompt is asynchronous, so you have to use it asynchronously.
Prompt 是异步的,所以你必须异步使用它。
var prompt = require('prompt')
, arr = [];
function getAnother() {
prompt.get('number', function(err, result) {
if (err) done();
else {
arr.push(parseInt(result.number, 10));
getAnother();
}
})
}
function done() {
console.log(arr);
}
prompt.start();
getAnother();
This will push numbers to arruntil you press Ctrl+C, at which point donewill be called.
这会将数字推送到arr直到您按Ctrl+ C,此时done将被调用。
回答by Rick
For those that do not want to import yet another module you can use the standard nodejs process.
对于那些不想导入另一个模块的人,您可以使用标准的 nodejs 流程。
function prompt(question, callback) {
var stdin = process.stdin,
stdout = process.stdout;
stdin.resume();
stdout.write(question);
stdin.once('data', function (data) {
callback(data.toString().trim());
});
}
Use case
用例
prompt('Whats your name?', function (input) {
console.log(input);
process.exit();
});
回答by Govind Rai
Modern Node.js Example w/ ES6 Promises & no third-party libraries.
现代 Node.js 示例,带有 ES6 Promises,没有第三方库。
Rick has provided a great starting point, but here is a more complete example of how one prompt question after question and be able to reference those answers later. Since reading/writing is asynchronous, promises/callbacks are the only way to code such a flow in JavaScript.
Rick 提供了一个很好的起点,但这里有一个更完整的示例,说明如何提示一个又一个问题,并在以后能够参考这些答案。由于读/写是异步的,promises/callbacks 是在 JavaScript 中编写这种流程的唯一方法。
const { stdin, stdout } = process;
function prompt(question) {
return new Promise((resolve, reject) => {
stdin.resume();
stdout.write(question);
stdin.on('data', data => resolve(data.toString().trim()));
stdin.on('error', err => reject(err));
});
}
async function main() {
try {
const name = await prompt("What's your name? ")
const age = await prompt("What's your age? ");
const email = await prompt("What's your email address? ");
const user = { name, age, email };
console.log(user);
stdin.pause();
} catch(error) {
console.log("There's an error!");
console.log(error);
}
process.exit();
}
main();
回答by Shay
Node.js has implemented a simple readline module that does it asynchronously:
Node.js 实现了一个简单的 readline 模块,它异步执行:
https://nodejs.org/api/readline.html
https://nodejs.org/api/readline.html
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
});

