How to read from local .csv file in javascript to fill an array of strings?

816 Views Asked by At

I have a CSV file with 100 names per line. I want to create an array containing each name. Currently, my CSV file looks like this:

Names
Bob
Joe
Tim
Allan 

and I want to fill the array as follows:

const csv = require('csv-parser');
const fs = require('fs');    
const names= [];
fs.createReadStream('./Names.csv')
  .pipe(csv())
  .on('data', (data) => names.push(data.Names))
  .on('error', (error) => loggingService.getDefaultLogger().error(error))
  .on('end', () => loggingService.getDefaultLogger().info("Array of Names:" + names));

Using a logging service I've created I see all names from the CSV. When I do console.log(names) I get an empty array. Might anyone know why this is? More specifically is there a better way to read from a CSV file so that I can fill an array of strings with the contents of that file, 1 array entry as a string per line?

1

There are 1 best solutions below

0
On

May work but not sure.

Edit: Yup working like a charm.

const fs = require('fs');

let Names = [];

fs.readFile('./names.csv', 'utf8', (err, dat) => {
  if(err)
    console.error("Error while opening file");

  Names = String(dat).split('\n');
});