附加到字符串的范围问题

Scope issue appending to string

我正在尝试使用节点 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);

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