Search code examples
javascriptnode.jsarrayscsvcsv-parser

Parse csv using "csv-parser" node JS


I am using the 'csv-parser' library. Using the method below I am able to get the data stored in the birthdays array shown in the console:

    const birthdays = [];  
fs.createReadStream('./data/groupes.csv')
        .pipe(csv({}))
        .on('data', (data) => birthdays.push(data))
        .on('end', () => {
          console.log(birthdays)
      });

but when I log outside the .on('end') like below, the console shows the birthdays array as empty:

    const birthdays = [];  
fs.createReadStream('./data/groupes.csv')
        .pipe(csv({}))
        .on('data', (data) => birthdays.push(data))
        .on('end', () => {
      });
      console.log(birthdays)

Why is that? and how can I solve it? Thanks in advance.


Solution

  • Why is that?

    It's because createReadStream is working asynchronously and when you console.log(birthdays); outside, the code execution reads the log before createReadStream has finished processing

    how can I solve it?

    You were correct to put it inside the .on("end")

    const birthdays = [];  
    fs.createReadStream('./data/groupes.csv')
        .pipe(csv({}))
        .on('data', (data) => birthdays.push(data))
        .on('end', () => {
          console.log(birthdays);
          // further processing with birthdays
      });