How to extract data from a csv file in nodejs

var fs = require('fs');
var csv = require('csv');

csv()
 .from.stream(fs.createReadStream('nodetest.csv'))
 .to.array(function(data, count) {
    var lastLine = data.slice(-1)[0];
    var needed = lastLine.slice(-1)[0];
    console.log(needed);
  });

I'm trying to extract some data from a csv file. Lets say my csv file contains these rows

ABB|BCC|CDD|DEE eff|fgg||ghh|hii ijj|JKK|kll|LMM

and I only need to extractkll from the last line

Upvotes: 0

Views: 2113

Answers (1)

severin.julien
severin.julien

Reputation: 1354

I guess you are using this npm module : csv.

You can use a simplier code to parse your CSV. And for extracting the needed value you could do :

var fs = require('fs');
var csv = require('csv');

var parser = csv.parse({delimiter: '|'}, function(err, data){
    var lastRow = data[data.length-1];
    var wantedValue = lastRow[lastRow.length-2];
    console.log(wantedValue);
});

fs.createReadStream(__dirname+'/file.csv').pipe(parser);

Notice that this code is static, but it meet your requirement. Your CSV must stay the same. Notice that I set | as a delimiter. By default CSV use the coma delimiter (hence the name Comma Separated Values).

The documentation for the parser can be found here.

Upvotes: 3

Related Questions