简体   繁体   English

如何在node.js中读取多个csv文件

[英]How to read multiple csv files in node.js

I'm trying to read multiple csv files and then add them as properties to an object, but the async of node.js really prevents me from doing this. 我正在尝试读取多个csv文件,然后将它们作为属性添加到对象,但是node.js的异步确实阻止了我这样做。

This is the code I tried. 这是我尝试的代码。

var Converter=require("csvtojson").core.Converter; 
var fs = require('fs');
var csvConverter=new Converter();
var data = {};

for (var i = 0; i < 10; i++)
{   
    var csvFileName="./data/String(i)".csv";

    csvConverter.on("end_parsed",function(jsonObj){
    data['file'+String(i)] = json;


    //read from file
    fs.createReadStream(csvFileName).pipe(csvConverter);
});

} }

This leads to a horrible mess, as the for-loop finishes before any of the events are triggered. 这会导致可怕的混乱,因为for循环在触发任何事件之前就已完成。 I would really prefer a synchronous solution to this, but I understand that node.js simply isn't built for that. 我真的更喜欢使用同步解决方案,但是我知道node.js并不是为此而构建的。

So I would be pleased if someone could help me understand how to fix this async. 因此,如果有人可以帮助我了解如何解决此异步问题,我将感到非常高兴。 However, this is the first time I've had such a problem. 但是,这是我第一次遇到这样的问题。 An hour ago I didn't know about the concept asynchronous code. 一个小时前,我不了解异步代码的概念。

i is problematic since you can't predict what it is going to be inside the end_parsed callback function, so try: i有问题,因为您无法预测end_parsed回调函数中的内容,因此请尝试:

var fileIndex = 0;
csvConverter.on('end_parsed', function (json) {
    data['file' + fileIndex] = json;
    if (fileIndex === 9) {
       // It is done, call the callback to finish processing
       callback(data);
    }
    fileIndex += 1;
});

var callback = function (data) {
    // Put callback code here
    console.log(data.file0);
};

Really the best way to solve this is to use Promises . 解决这个问题的最好方法是使用Promises

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM