NodeJs csv模块-暂停和恢复

voj3qocg  于 2023-09-27  发布在  其他
关注(0)|答案(2)|浏览(96)

我正在使用nodeJs的csv模块来解析一个10000条记录的大csv,在每条记录上,即.on('record',func),我必须实现一个耗时的逻辑。但是节点不会等到我完成。我该怎么办?docu讨论了http://www.adaltas.com/projects/node-csv/ pause()和resume()。但是我在哪里使用它呢?

var csv = require('csv');
    var fs = require('fs');
    csv()
    .from.stream(fs.createReadStream(__dirname+'/sample.in'))
    .to.path(__dirname+'/sample.out')
    .transform( function(row){
      row.unshift(row.pop());
      return row;
    })
    .on('record', function(row,index){
              //Time consuming logic goes here
    })
    .on('end', function(count){
      console.log('Number of lines: '+count);
    })
    .on('error', function(error){
      console.log(error.message);
    });
efzxgjgh

efzxgjgh1#

我终于把它修好了。感谢node-csv开发人员

//Read through the csv file one row at a time
csv()
    .from(__dirname+'data.csv', { columns: true })
    .transform(function(row, index, next){
         setTimeout(function(){
         console.log(row);
         next()
         }, 3000); //replace setTimeout with any fn and call next() in the callback

    }, {parallel: 1})
    .on("end", function (count) {
      var finalcount = count;
      var logtext = 'SUMMARY: Total count: ' + finalcount + '\n' 
                    + 'Error count:' + errorcount  + "("+errorArray+")"
                    + '\n' + 'Success count:' + successcount;
      fs.appendFile(config.logfilename, '\n'+ logtext, function (err) {
        console.log(logtext);
      });  

      console.log("done", count);
    });
nimxete2

nimxete22#

这是我如何在nodejs中使用fast-csv模块来处理大文件。

require('colors');

const fs = require('fs');
const fastcsv = require('fast-csv');
const file = './path-to-your-file.csv';
const stream = fs.createReadStream(file);

const parser = fastcsv
  .parseStream(stream, { headers: true })
  .on('data', async function (item) {
    parser.pause();
    // any async func here
    await doSomethingWithDB(item);

    parser.resume();
  })
  .on('end', async (rowCount) => {
    console.log(`Parsed ${rowCount} rows`.green);
  });

相关问题