Synchronous processing of a csv file using fast-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 I encountered is that the process is not synchronous. The result that I see is similar to

here
here
inside saving
inside saving

But, I want

here
inside saving
here
inside saving

I assume that we need to use async.series or async.eachSeries, but not quite exactly how to use it. Any inputs are welcome.

Thank Advance

+4
source share
1 answer

, saveData :

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);
}
+7

All Articles