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

208
Visualizações
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 Respostas
Responde à pergunta

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