Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse CSV in nodejs and get the content array accessible outside of 'end' closure?

Using the csv-parse module in node to parse some CSV file getting the content of the file as an array:

var fs = require('fs'); 
var parse = require('csv-parse');

var words=[];
fs.createReadStream("5.csv")
    .pipe(parse({delimiter: ','}))
    .on('data', function(csvrow) {
        //console.log(csvrow);
        //do something with csvrow
        words.push(csvrow);        
    })
    .on('end',function() {
      //do something with words
      //console.log(words);
    });
console.log(words);

Why does this code returns:

[]

An empty array? Seems it’s scoped inside the ‘end’ closure.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I make words variable accessible to the outside at end of the parsing here?

>Solution :

fs.createReadStream is asyncronous: you can (for example) wrap it into a promise to get the value after the stream has ended:

const fs = require('fs'); 
const parse = require('csv-parse');

async function readWords() {
  const promise = () => new Promise((resolve, reject) => {
    const words=[];

    fs.createReadStream("5.csv")
      .pipe(parse({delimiter: ','}))
      .on('data', function(csvrow) {
        //console.log(csvrow);
        //do something with csvrow
        words.push(csvrow);        
    })
    .on('end',function() {
      resolve(words)
    })
    .on('error', function(err) {
      reject(err);
    });
  });

  const words = await promise();
  console.log(words);
}

readWords();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading