【问题标题】:Scope issue appending to string附加到字符串的范围问题
【发布时间】:2015-01-13 00:53:49
【问题描述】:

我正在尝试使用节点 csvtojson 库转换 CSV 文件,在文件中查找某些数据,将数据添加到字符串,然后记录字符串(最终我会将其写入文本文件)。

JSON 对象很好,我可以从函数中记录数据,但我不能使用 += 将它附加到我的字符串中。我认为这是一个范围问题,但我不确定我哪里出错了。

//Converter Class
var Converter=require("csvtojson").core.Converter;

var fs=require("fs");

var capsuleFile="capsule-contacts.csv";
var capsuleFileStream=fs.createReadStream(capsuleFile);

//new csv to json converter instance
var csvConverter=new Converter({constructResult:true});

var fileToWrite = "";

csvConverter.on("end_parsed",function(jsonObj){
   for(var i = 0; i < jsonObj.length; i++) {
    if(jsonObj[i].Type == "Organisation") {
        console.log(jsonObj[i].Organisation.toString()); //this works
        fileToWrite += jsonObj[i].Organisation.toString();  
        fileToWrite += "     -     ";
        fileToWrite += jsonObj[i]["Email Address"].toString();
        fileToWrite += "     -     ";
        fileToWrite += jsonObj[i]["Work Phone"].toString();
        fileToWrite += "\n";
        console.log(fileToWrite); //this works
    }
   }

});

//this does not work
console.log(fileToWrite);

【问题讨论】:

    标签: javascript string node.js scope


    【解决方案1】:

    csvtojson 执行转换异步,所以你不能指望console.log(fileToWrite); 显示正确的输出,因为end_parsed 事件直到某个时间才会发生未来,在您的console.log(fileToWrite); 执行之后。欢迎来到异步编程(和 node.js)的世界。

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 2023-03-08
      • 2014-06-21
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多