Node.js CSV 转 JSON(大文件)

4
我需要将csv文件中的行转换为json格式。我使用了csvtojson包,它非常好用,但我的csv文件非常大,有2100万行。:(
我的node应用程序无法处理所有行。
请查看下面的代码片段。
csv({noheader:true,
      delimiter:";",
    workerNum: 4})
  .fromFile(csvFilePath)
  .on('json',(jsonObj, rowIndex)=>{
      var TN = jsonObj.field1;
      var cod_op = jsonObj.field2;
      var msisdn = TN.toString();

     //UP TO FIREBASE HERE!!!

        noticia.child(msisdn).set(cod_op);
        console.log(TN + ' ' + rowIndex);



  })
  .on('done',(error)=>{
      console.log()
  })
1个回答

3

我使用了 csv-stream 模块 成功解决了问题。

这里是一个片段:

  var options = {
    delimiter : ';', // default is ,
    endLine : '\n', // default is \n,
    columns : ['VERSION_ID', 'TN','RN1','DATA','OPERACAO','CNL','EOT'], // by default read the first line and use values found as columns
    columnOffset : 7, // default is 0
    escapeChar : '"', // default is an empty string
    enclosedChar : '"' // default is an empty string
}

var csvStream = csv.createStream(options);
i = 0
request('http://yourhugefile.csv').pipe(csvStream)
    .on('error',function(err){
        console.error(err);
    })
    .on('data',function(data){
        // outputs an object containing a set of key/value pair representing a line found in the csv file.
        //console.log(data);
    })
    .on('column',function(key,value){
      if(key == 'TN' || key == 'RN1')
          firebaseUpload(value);
        // outputs the column name associated with the value found
        //console.log('#' + key + ' = ' + value);
    })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接