I'm trying to read multiple csv files and then add them as properties to an object, but the async of node.js really prevents me from doing this.
This is the code I tried.
var Converter=require("csvtojson").core.Converter;
var fs = require('fs');
var csvConverter=new Converter();
var data = {};
for (var i = 0; i < 10; i++)
{
var csvFileName="./data/String(i)".csv";
csvConverter.on("end_parsed",function(jsonObj){
data['file'+String(i)] = json;
//read from file
fs.createReadStream(csvFileName).pipe(csvConverter);
});
}
This leads to a horrible mess, as the for-loop finishes before any of the events are triggered. I would really prefer a synchronous solution to this, but I understand that node.js simply isn't built for that.
So I would be pleased if someone could help me understand how to fix this async. However, this is the first time I've had such a problem. An hour ago I didn't know about the concept asynchronous code.