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

Time:11-15

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.

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

CodePudding user response:

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();
  • Related