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:
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.