使用fast-csv同步处理csv文件 [英] Synchronous processing of a csv file using fast-csv

查看:324
本文介绍了使用fast-csv同步处理csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用fast-csv处理一个csv文件,这是我的代码.

I am trying to process a csv file using fast-csv and here is my code.

    var stream = fs.createReadStream("sample.csv");
    csv.fromStream(stream, {headers : true})
    .on("data", function(data) {
            console.log('here');
            module.exports.saveData(data, callback)
        })
    .on("end", function(){
        console.log('end of saving file');
    });

    module.exports.saveData = function(data) {
    console.log('inside saving')
    }

我面临的问题是过程不同步. 我看到的输出类似

The problem that I am facing is the process is not synchronous. The output that I am seeing is something like

此处
在这里
内部保存
内部保存

here
here
inside saving
inside saving

但是,我想要的是

此处
内部保存
在这里
内部保存

here
inside saving
here
inside saving

我假设我们需要使用async.series或async.eachSeries,但不能完全确定如何在此处使用它.任何输入都将不胜感激

I am assuming we need to use async.series or async.eachSeries but not exactly sure how to use that here. Any inputs are greatly appreciated

预先感谢!

推荐答案

您可以暂停解析器,等待saveData完成,然后恢复解析器:

You can pause the parser, wait for saveData to complete, and subsequently resume the parser:

var parser = csv.fromStream(stream, {headers : true}).on("data", function(data) {
  console.log('here');
  parser.pause();
  module.exports.saveData(data, function(err) {
    // TODO: handle error
    parser.resume();
  });
}).on("end", function(){
  console.log('end of saving file');
});

module.exports.saveData = function(data, callback) {
  console.log('inside saving')
  // Simulate an asynchronous operation:
  process.setImmediate(callback);
}

这篇关于使用fast-csv同步处理csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆