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).
csv-parser
seems to always be asynchronous, so you're out of luck there.
If data.csv
doesn't change often, I'd recommend parsing it into JSON once and then require
the JSON directly.
Otherwise, you can either implement synchronous CSV parsing yourself, or alternately refactor your code to wait until the asynchronous parsing is complete before carrying on with that data.