【问题标题】:Node.JS > save results from event emitterNode.JS > 保存来自事件发射器的结果
【发布时间】:2014-07-31 16:09:52
【问题描述】:

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

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

【问题讨论】:

    标签: node.js eventemitter


    【解决方案1】:

    这是范围和执行时间的问题。 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
    

    【讨论】:

    • 啊,哦,有道理。尽管如此,我如何才能获得结果以进一步使用它们?
    • 非常感谢,这对我有很大帮助,我已经探索过异步,这个解决方案现在很好用。
    【解决方案2】:

    原因是csvConverter.on() 只添加了一个事件处理程序。实际事件发生在未来某个时间,所以 res 直到那个时候才会设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多