Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
How to get data out of a stream?

I would have expected that I got all the CSV data in the array, but for some reason I don't get anything.

Can someone explain why a is empty at the end?

const fs = require('fs');
const { parse } = require('csv-parse');

let a = [];

fs.createReadStream('./example.csv')
   .pipe(parse({ delimiter: ';', from_line: 2 }))
   .on('data', function (row) {
      a.push(row);
   })
   .on('end', function () {
      console.log('finished');
   })
   .on('error', function (error) {
      console.log(error.message);
   });

console.log(a);
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

createReadStream() runs parallel. So after calling this function, the program continues and the next process is your console.log(a). Thats the idea behind streams because the program can continue running while the big file is read out.

The code inside the .on() functions is called later. Thats why they are called "callbacks".

So you are logging the result before any data is read...

about 4 years ago · Santiago Trujillo Denunciar

0

As explained before the headstream runs in the background. You can wrap the stream in a promise to get the result. Here is one possible solution:

const fs = require('fs');
const { parse } = require('csv-parse');

const readFile = async () => new Promise((resolve, reject) => {
    let a = [];
    fs.createReadStream('./example.csv')
        .pipe(parse({ delimiter: ';', from_line: 2 }))
        .on('data', function (row) {
            a.push(row);
        })
        .on('end', function () {
            resolve(a);
        })
        .on('error', function (error) {
            reject(error)
        });
});

readFile().then(data => console.log(data))
about 4 years ago · Santiago Trujillo Denunciar

0

Your a is undefined because the code is executed asynchronously. The on() function is called after your console.log(a) is executed.

You can read the value of a inside the data event or the end event:

fs.createReadStream('./example.csv')
   .pipe(parse({ delimiter: ';', from_line: 2 }))
   .on('data', function (row) {
      a.push(row);
      console.log(a) // <------- here
   })
   .on('end', function () {
      console.log('finished');
      console.log(a) // <------- here
   })
   .on('error', function (error) {
      console.log(error.message);
   });

One solution may be to use a Promise

const readCSVData = async () => new Promise((resolve, reject) => {
let a = []
fs.createReadStream('./example.csv')
   .pipe(parse({ delimiter: ';', from_line: 2 }))
   .on('data', function (row) {
      a.push(row);
   })
   .on('end', function () {
      // return the a value 
      resolve(a) 
   })
   .on('error', function (error) {
      reject(error)
   });
})

// ..... 

const foo = async () => {
  const data = await readCSVData()
  console.log(data)
}

// or
readCSVData().then(a => console.log(a))
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda