Node.JS>保存事件发射器的结果

时间:2014-07-31 16:09:52

标签: node.js eventemitter

这可能是一个可怕的菜鸟问题,但我在这里做错了。 为什么我的结果变量不能在.on()之外保存?我如何返回csvConverter.on的结果?

var res = ''; 
csvConverter.on("end_parsed",function(jsonObj) {
        res = jsonObj;
    });
console.log(res);
fileStream.pipe(csvConverter);

2 个答案:

答案 0 :(得分:0)

原因是csvConverter.on()只添加了一个事件处理程序。实际事件发生在将来的某个时间,因此res在此之前不会被设置。

答案 1 :(得分:0)

这是范围和执行时间的问题。 res = jsonObj将写入您的全局变量,但代码console.log(res);将更早执行,因此不会返回您正在查找的数据。


我假设你在这里使用https://github.com/Keyang/node-csvtojson ..

node.js利用回调来返回异步调用的数据,因此您可以将该功能包装到另一个函数中,并使用回调调用该函数:

//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

类似版本使用Async(https://github.com/caolan/async)瀑布:

    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