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

207
Vistas
node csv parsing return value comes back as undefined when called

Here is the code I am running

const fs = require('fs');
const csvParse = require('csv-parse');

function getValue() {
    let results = [];
    fs.createReadStream('./assets/myCSV.csv')
        .pipe(csvParse({delimiter: '\n'}))
        .on('data', (data) => results.push(data))
        .on('error', (err => {
            console.log(`csv-parse error from getValue: ${err}`);
        }))
        .on('end', () => {
            console.log('finished!');

            let csvLength = Object.keys(results).length;

            // getting a random value within the csv
            min = Math.ceil(0);
            max = Math.floor(csvLength);
            let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

            let randomCSVLine = results[randomNumber];

            console.log(randomCSVLine);

            return randomCSVLine;
        });
}

console.log(`mine: ${getValue()}`);

here are the results and I dont know why the value doesnt show. I think it could be an async issue but not sure how to solve it yet results:

mine: undefined
finished!
[ '10' ]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think you will find the solution here.

CSV Parser for Node.js Promises usage

Starting with Node.js version 15, the Stream API promise a new "stream/promises" module.

Part of the Stream Promises module is the finished function. The Function plugs into a stream and resolves a promise when it is no longer readable, writable or has experienced an error or a premature close event.

The promises example leverages pipe as well as finished to provide a convenient solution to read a file from the file system and to pipe its output into the parser.

This example is available with the command node samples/recipe.promises.js.

const parse = require('csv-parse');
const fs = require('fs');
const { finished } = require('stream/promises');
 
const processFile = async () => {
  records = []
  const parser = fs
  .createReadStream(`${__dirname}/fs_read.csv`)
  .pipe(parse({
    // CSV options if any
  }));
  parser.on('readable', function(){
    let record;
    while (record = parser.read()) {
      // Work with each record
      records.push(record)
    }
  });
  await finished(parser);
  return records
}

(async () => {
  const records = await processFile()
  console.info(records);
})()

Just need to make same changes to your code to achieve the desired results.

about 4 years ago · Juan Pablo Isaza 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