0

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' ]
AugustusCaesar
  • 175
  • 2
  • 14

1 Answers1

3

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.

ManuelMB
  • 1,254
  • 2
  • 8
  • 16