0

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?

4
  • I wonder where your console.log() statement is? If after presented code - yes names would be empty because reading is asynchronous and you getting to console faster than finish reading from file Commented Sep 30, 2020 at 22:44
  • I'm not familiar with the CSV library, but in the following snippet, where does devices come from ? (data) => devices.push(data.Names) Commented Sep 30, 2020 at 22:45
  • @bensiu It is after the code snippet. If I want to iterate through the array of names and do something with them, how would I overcome the asynchronous reading? Ideally I want to fill the array, then do a forEach element in the array, create a new object. Before that forEach the I'm not sure the names array would be full. Commented Sep 30, 2020 at 22:56
  • @Hassan that was a typo. it should be: names.push(data.Names). Commented Sep 30, 2020 at 22:57

1 Answer 1

1

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');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.