Synchronously read csv file row by row nodejs

Viewed 2501

I want to parse a csv file of 1000 rows one by one and perform action on each row. I am using fast-csv npm module. My code is reading csv file asynchronously and performing action, after complete file is read which is not according to my requirement.

exports.readCSV = function readCSV(fname, next) {
    var csv = require("fast-csv");     
    csv    
        .fromPath(path.join(__dirname, '/csv/'+fname) )
        .on('error', function(error) {
            next(null, {
                success: false,
                result: '',
                msg: 'Error reading server file'
            });
        })
        .on("data", function(data){
            console.log("read row");
            exports.dosomething(data);
        })
        .on("end",function(){
        })
}

exports.dosomething = function dosomething(data) {
    console.log("in dosomething");
};

Output I get is

read row
read row
in dosomething
in dosomething

However, expected output is

read row
in dosomething
read row
in dosomething

Any help will be highly appreciated.

0 Answers
Related