Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Adding data to an array and accessing the data inside the array outside the function Javascript

I'm new to Javascript and I'm not understanding how to persist data in an array. In my function I'm reading a file line by line and saving it in an array. I figured that because the array is declared outside the function that data would remain in it, but that's not what happens. I would like to understand how to do when printing the values ​​of the array outside the function that data still remain.

My code:

const fs = require('fs');
const readline = require('readline');
  
var array = [];


async function processLineByLine() {
  const fileStream = fs.createReadStream('data.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity,
  });

  for await (const line of rl) {
    
      array.push(line);
    }
 

  //console.log(array.toString());
}

processLineByLine();
console.log(array.toString());

The expected output would be to have the data inside the array:

288355555123888,335333555584333,223343555124001,002111555874555,111188555654777,111333555123333
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because processLineByLine is an async function the console.log runs before the async has populated the array.

You need to log after the async function has completed, as shown below:

processLineByLine().then(() => console.log(array.toString()));

Also, you don't need to declare the array outside the function, you can move it inside the function and return it from there and that would passed as an argument to the .then callback, as shown below:

const fs = require("fs");
const readline = require("readline");

async function processLineByLine() {
  const array = [];
  const fileStream = fs.createReadStream("data.txt");

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity,
  });

  for await (const line of rl) {
    array.push(line);
  }

  return array;
}

processLineByLine().then((array) => console.log(array.toString()));
about 4 years ago · Juan Pablo Isaza Relatório

0

You wont get since it's async call. try below snippet

const fs = require('fs');
const readline = require('readline');

var array = [];

async function processLineByLine() {
    const fileStream = fs.createReadStream('data.txt');
    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity,
    });

    for await (const line of rl) {  
        array.push(line);
    }
}

processLineByLine().then(()=>{
    console.log(array);
});

if each line of data.txt is like 288355555123888, 335333555584333, 223343555124001,... and want to extract those numbers spit each line and then add it to array.

for await (const line of rl) {  
    array=[...array, ...line.split(',')];
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda