Gregion Gregion - 2 months ago 13
Javascript Question

Passing csvtojson converter's value to a variable outside of its scope

I'm currently fiddling around with Node.js and I stuck with this issue.

I'm using the csvtojson converter (https://github.com/Keyang/node-csvtojson) as a separate module that I can call in my other JS files as many times as I want.

Here is my tools.js:



module.exports = {
csvToJson: function (csvPath) {
var Converter = require('csvtojson').Converter;
var converter = new Converter({});
var transfer = "DEFAULT";
converter.fromFile(csvPath, function(err, result){
if (err) {
return console.log(err);
}
else {
transfer = result;
}
});
return transfer;
}
};





And here is how I call it:



var countriesCsvFile = path.join(__dirname, '..', 'testDataFiles', 'countries.csv');

//GRAB TOOLS
var tools = require('../app/tools');
console.log(tools.csvToJson(countriesCsvFile));





The result is always the "DEFAULT" value which indicates, that the converter is not touching it.

I want to pass it as the return value of the function, to further be able to process the data on the fly, without creating a file, and read that.
It is surely some scope issue, but after scratching my scalp for a few hours, and browsing the questions I couldn't retrieve anything remotely useful.

Also, another note: If I call console.log(result) instead of transfer = result, it shows me my precious and desired data.

Answer

You have to pass in a callback function because the csvToJson function is returning 'transfer' before any value is assigned to it. Like Sirko said, it's asynchronous. You can also use promises instead of callbacks but that's another topic in itself.

module.exports = {
  csvToJson: function (csvPath, callback) {
    var Converter = require('csvtojson').Converter;
    var converter = new Converter({});
    converter.fromFile(csvPath, function(err, result){
      if (err) {
        callback(err);
      }
      else {
        callback(null, result);
      }
    });
  }
};