2016-07-14 43 views
4

我正在嘗試使用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,但不完全確定如何在這裏使用。任何輸入將不勝感激

在此先感謝!

+0

所以,你要等待'saveDate'繼續解析CSV數據的下一行之前完成? – robertklep

+0

是的。這是正確的 –

回答

7

您可以暫停解析器,等待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); 
} 
+1

工作。謝謝! :) –