0

I am trying to get values for an array interactively from command line. Below is the code I have written for the same:

    const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
    });
      
    readline.question(`Enter Size of the array:`, (size) => {
    if(parseInt(size) > 0)
    {
        var a = new Array(size);
        var i = 0;
        debugger;
        // Get process.stdin as the standard input object.
        var standard_input = process.stdin;
    
        // Set input character encoding.
        standard_input.setEncoding('utf-8');
    
        // Prompt user to input data in console.
        console.log("Please input Array Elements.");
    
        // When user input data and click enter key.
        standard_input.on('data', function (data) {
    
            // User input exit.
            if(i > size){
                // Program exit.
                console.log("User input complete");
                process.exit();
            }else
            {
                a[i] = parseInt(data);
                // Print user input in console.
                console.log('User Input Data : ' + data);
                i++;
            }
        });
    
        for(var j = 0; j < size; j++){
            console.log(a[j]);
        }
    }
    readline.close();
    });

But I am not able to enter values of the array. After obtaining the size of the array the program just finishes by displaying undefined for array values like below: enter image description here

So could anybody let me know the proper way to accept inputs from command line interactively in Node.js.

I followed an answer from the below SO Link: Reading value from console, interactively

My code now looks like:

var a = [4,6,1,7,9,5];
var b = new Array(5);
var k = 7, t = 0, j = 0;

var question = function(q) {
    return new Promise( (res, rej) => {
        readline.question( q, answer => {
            res(answer);
        })
    });
};

(async function main() {
    var answer;
    while ( j < b.length ) {
        answer = await question('Enter an element ');
        b[j] = parseInt(answer);
        j++;
    }
    for(var i = 0; i < b.length; i++) {
        if(k === a[i]) {
            t = 1;
            break;
        }
    }
    
    if(t === 1 ){
        console.log(`Element ${k} found at position ${i}`);
        process.exit();
    } else {
        console.log(`Element Not Found`);
    }
})();

It is working fine. Let me know if anybody have a better solution. Thanks in Advance.

Abhilash D K
  • 1,223
  • 1
  • 23
  • 39
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Yury Tarabanko May 27 '19 at 06:07
  • @YuryTarabanko I understand the fact that I have to perform any actions inside the callback of an ASYNC function and I am doing it. I am declaring the array and trying to read values and all inside the callback. But when I debug the code the control never steps into `standard_input.on('data', function (data) {}`. I would like to understand why this happens. As per my understanding I am not running any async code inside the callback. So inside the callback function everything is synchronous right? – Abhilash D K May 27 '19 at 07:07

0 Answers0