Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
  });
about 4 years ago · Juan Pablo Isaza Report

0

Could you do something like this?

const csv = require("csv-parser");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const readFile = promisify(fs.readFile);

const birthdays = [];

const filePath = path.join(__dirname, "data", "groupes.csv");

readFile(filePath, "utf8").then((data) => {
  csv(data, {
    separator: ",",
  })
    .on("data", (row) => {
      birthdays.push(row);
    })
    .on("end", () => {
      console.log(birthdays);
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!