vamosrafa vamosrafa - 3 months ago 7x
Node.js Question

User input in 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.

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.

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


while(i!== "QUIT")
i = require('prompt');

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.


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

function done() {


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