Receive array values from console

1

I'm starting the node studies and I decided to do an exercise in which I need to receive a value n through the node console, which will be the number of elements in an array and receive n elements through the node console. The problem is that I do not know how to get the array elements from the console The code I have so far:

var readline = require('readline');
var valor = 0;
var valor1 = 0;
var conj = [];

var leitor = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

leitor.question("Digite a quantidade de itens do conjunto: ", 
function(resp,vet){
    valor = resp;
    for(var i = 0; i<valor; i++){
        console.log("Digite o valor de indice "+i);
        valor1 = vet;
        conj.push(valor1);
    }
    console.log(conj);
    leitor.close();
});
    
asked by anonymous 01.01.2019 / 23:17

1 answer

2

There are some minor problems with your code.

First: The callback function of the reader.question () method receives only one argument , which is the string that the user typed. That is, it would look like this:

leitor.question("Digite a quantidade de itens do conjunto: ", function(resp){

This leads us to another problem: Inside for , we would have to ask to enter a value for each index, right? That is:

for(var i = 0; i < resp; i++){
    leitor.question('Digite o valor de indice ' + i, (valor) => {
        conj.push(valor); 
    });
}

The problem is that for does not wait for the user to enter and the reader.question () method completes. So in a case where I want a set with only three elements, this would happen:

> Digite a quantidade de itens do conjunto: 3
> Digite o valor de indice 0Digite o valor de indice 0Digite o valor de indice 0[]

Perceived? One way to resolve this is with a asynchronous function . I gave some other improvements in your code, but it would look something like this:

const readline = require('readline');
const leitor = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const conj = [];

leitor.question('Digite a quantidade de itens do conjunto: ', async (quantidade) => {
    for(let i = 0; i < quantidade; i++) {
        // O await espera pelo retorno da Promise
        await new Promise((resolve) => { 
            leitor.question('Digite o valor de indice ${i}: ', (valor) => {
                resolve(conj.push(valor)); // A promise resolve e retorna
            });
        });
    }
    leitor.close();
    console.log(conj);
});
    
02.01.2019 / 07:36