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

190
Views
NodeJs Csv parser async operations

I'm trying to read a csv file, fetch data for every record on csv do some operations and at the end (after all of the async operations are complete) write a new csv file here is the code:

async function readInputCsv() {

  results = [];
  fs.createReadStream('./example_short.csv')
.pipe(csv())
.on('data', async function(data){
        console.log("trying for name: ", data.username);
        let edu = await getLastEducation(data.username);
        results.push({
          name: data.username,
          level: edu
        })
        console.log(data.username,": ", edu)
}).on("end", () => {
  console.log("end ! ");
  writeCsv(results);

});
}

What happens is "end !" gets printed before the getLastEducation function returns the responses

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

fs.createReadStream().on() does not accept Promises as second argument.

on(event: string, listener: (...args: any[]) => void): this;

about 4 years ago · Santiago Gelvez Report

0

First of all the results in this case is a global variable. I would suggest you to use let keyword to declare it within the scope of the function.

What is happening in this case is the time taken by the getLastEducation() for the async operation is more than the time required to the example_short.csv file.

To avoid this, add await keyword before fs.createReadStream() and move the writeCsv() function (I am assuming you are using csv-writer inside this function) after the entire read operation. The await keyword will make it wait until the async fetching operation is done.

async function readInputCsv() {
  let results = [];

  await fs
    .createReadStream('./example_short.csv')
    .pipe(csv())
    .on('data', async function (data) {
      console.log('trying for name: ', data.username);
      let edu = await getLastEducation(data.username);
      results.push({
        name: data.username,
        level: edu,
      });
      console.log(data.username, ': ', edu);
    })
    .on('end', () => {
      console.log('end ! ');
    });

  writeCsv(results);
}
about 4 years ago · Santiago Gelvez 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!