This is a question of scope and execution time. res = jsonObj
will write into your global variable, but the code console.log(res);
will be executed earlier and thus will not return the data you're looking for.
I'm assuming you are using https://github.com/Keyang/node-csvtojson here..
node.js utilizes callbacks to return data for asynchronous calls, so you could either wrap the functionality into another function, which you call with your callback:
//Converter Class
var Converter = require("csvtojson").core.Converter;
var fs = require("fs");
function readCsv(csvFileName, callback) {
var fileStream = fs.createReadStream(csvFileName);
//new converter instance
var csvConverter = new Converter({constructResult: true});
//end_parsed will be emitted once parsing finished
csvConverter.on("end_parsed", function (jsonObj) {
callback(jsonObj)
});
//read from file
fileStream.pipe(csvConverter);
}
readCsv("./myCSVFile", function(result) {
console.log(result); // or do whatever you want with the data
// or continue with your program flow from here
});
// code written here will be executed before reading your file
// so simply don't put anything here at all
A similar version utilizes Async's (https://github.com/caolan/async) waterfall:
var Converter = require("csvtojson").core.Converter;
var fs = require("fs");
var async = require('async');
async.waterfall([
function(callback){
var csvFileName = "./myCSVFile";
var fileStream = fs.createReadStream(csvFileName);
//new converter instance
var csvConverter = new Converter({constructResult: true});
//end_parsed will be emitted once parsing finished
csvConverter.on("end_parsed", function (jsonObj) {
callback(null, jsonObj)
});
//read from file
fileStream.pipe(csvConverter);
}
], function (err, result) {
console.log(result); // or do whatever you want with the data
// or continue with your program flow from here
});
// code written here will be executed before reading your file
// so simply don't put anything here at all