Mazino
Mazino

Reputation: 356

Reading from a CSV in NodeJS

Problem

The push() function inside the createReadStream does not push my data to the array.

The Code

let csv = require('csv-parser');

let people = [];

let final_array = [];

fs.createReadStream('people.csv')
      .pipe(csv())
      .on('data', (data) => {
        people.push(data)
      })
      .on('end', () => {
        console.log(people) //This prints out people fine
      })

console.log(people) //This returns empty array

people.forEach((names) => {
    console.log(people[names]); //absolutely no output
})

The Output

[] //Output for console.log(people) outside the createReadStream

//Output for console.log  people inside the createReadStream
[
  { username: 'rezero' },
  { username: 'software' },
  { username: 'planets' },
  { username: 'darkseid' },
  { username: 'gintama' },
  { username: 'websines' },
  { username: 'digital' }
]

Desired Output

I want only the usernames from the data to go into my final_array for further tasks.

final_array = ['rezero','software','planets','darkseid','gintama','websines','digital']

Upvotes: 1

Views: 64

Answers (1)

eol
eol

Reputation: 24555

The csv-parsing will run asynchronously, which means console.log(people) (and the code after that) will run before the file was parsed completely.

You could wrap the parsing into a promise and await this promise (this still needs error handling, but should give you an idea):

(async () => {
    let peopleData = [];
    await new Promise(resolve => {
        fs.createReadStream('people.csv')
            .pipe(csv())
            .on('data', (data) => {
                peopleData.push(data)
            })
            .on('end', () => {
                resolve();
            })
    });
    const finalArray = peopleData.map(data => data.username);
    finalArray.forEach(name => {
      console.log(name);
    });
    
})();

Upvotes: 1

Related Questions