用户在Node.js中input

我正在编写一个程序,它将创build一个数组数组,并将每个数组的内容加倍,并将结果存储为键/值对。 此前,我已经硬编码arrays,所以一切都很好。

现在,我已经改变了一点逻辑,我想从用户的input,然后,将值存储在一个数组中。

我的问题是,我无法弄清楚,如何使用node.js做到这一点。 我已经使用npm安装提示安装了提示模块,也已经通过文档,但没有任何工作。

我知道我在这里犯了一个小错误。

这是我的代码:

//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 

请帮助我,谢谢。

提示是asynchronous的,所以你必须asynchronous使用它。

 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(); 

这将把数字推到arr直到你按下Ctrl + C ,在这一点上将被调用。

对于那些不想导入另一个模块的用户,可以使用标准的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()); }); } 

用例

 prompt('Whats your name?', function (input) { console.log(input); process.exit(); });