0

This is probably a horrible noob question, but I am doing something wrong here. Why won't my result variable not save outside of .on()? How would I return the results of csvConverter.on ?

var res = ''; 
csvConverter.on("end_parsed",function(jsonObj) {
        res = jsonObj;
    });
console.log(res);
fileStream.pipe(csvConverter);
gattermeier
  • 471
  • 1
  • 5
  • 11

2 Answers2

0

The reason is that csvConverter.on() only adds an event handler. The actual event occurs some time in the future, so res won't be set until that time.

mscdex
  • 104,356
  • 15
  • 192
  • 153
0

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
Kevin Sandow
  • 4,003
  • 1
  • 20
  • 33