Is there a way to read CSV in node.js synchronously?

I am parsing CSV in node.js using csv-parser lib. But I need that parsed data would be avaliable in the whole project, not only in ‘fs’ section. I know that there is fs.readFileSync option but it does not useful since CSV is binary file (at least in node.js interpretation). What should I do?

const csv = require("csv-parser");
const fs = require("fs");


const cities = [];


let content = fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (row) => {
    cities.push(row);
  });

  

var city_data = {
    createArrayId: function(){
        console.log(cities);
        return cities;
    }
}

module.exports = city_data;

As you can see, I need to export "cities" array. Right now it returns empty value (initialized value).

62 thoughts on “Is there a way to read CSV in node.js synchronously?”

Leave a Comment