Home Using csv-parse with callback
Reply: 0

Using csv-parse with callback

Alboss
1#
Alboss Published in 2017-11-14 15:49:47Z

I am trying to parse csv using npm module csv-parse and then be able to call it elsewhere to get the parsed json array:

var inputArray = [];
var csv = require('csv-parser');
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require('fs'));

function tripParser(inputCsv) {
     fs.createReadStream(inputCsv)
        .pipe(csv())
        .on('data', function (data) {
            var jsonObject = {
                _id: data.TripID
            };
            //push it to array
            inputArray.push(jsonObject);
        })
        .on('end', function() {
            console.log("Finished processing csv file to json array...");
            return Promise.all(inputArray);
        });
}

and in different file, when I call this function, I want the parsed json array:

var tripParser = require('./tripParser');

console.log("parsing begins...");
tripParser("./small_sample_rides.csv").then(function (jsonArray) {
    console.log("Parsed Data: ");
    console.log(jsonArray);
});

I attempted to implement some sort of callback using bluebird, but it seems that I am using it wrong. I am getting nothing from the other file. I also attempted to have tripParser function return

return fs.createReadStreamAsync(inputCsv)
.pipe(csv()) 
...

but none of this approach seemed to be working. How do I properly handle the promises to get the jsonArray elsewhere?? Thanks!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301156 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO