用户在Node.js中的输入 [英] User input in Node.js

查看:53
本文介绍了用户在Node.js中的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序将创建一个数字数组,并将每个数组的内容加倍,并将结果存储为键/值对.之前,我已经对数组进行了硬编码,所以一切都很好.

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.

我的问题是我无法弄清楚如何使用node.js做到这一点.我已经使用npm install提示安装了提示模块,并且已经阅读了文档,但是没有任何效果.

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.

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

I know that I am making a small mistake here.

这是我的代码:

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

请帮助我,谢谢.

推荐答案

提示是异步的,因此您必须异步使用它.

Prompt is asynchronous, so you have to use it asynchronously.

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 ,此时 done 叫.

This will push numbers to arr until you press Ctrl+C, at which point done will be called.

这篇关于用户在Node.js中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆