使用fast-csv同步处理一个csv文件

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

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') } 

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

这里
这里
里面保存
里面保存

但是,我想要的是

这里
里面保存
这里
里面保存

我假设我们需要使用async.series或async.eachSeries,但不完全确定如何在这里使用。 任何input,不胜感激

提前致谢!

您可以暂停parsing器,等待saveData完成,然后继续parsing器:

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