Ann
Ann

Reputation: 206

How to read data columnwise from csv file in nodejs?

I've used the 'fast-csv' module to parse the csv file for other manipulations, but that returns data row-wise. I want to read the first 2 columns of a csv file. Can someone please help?

Upvotes: 0

Views: 2825

Answers (1)

cyberwombat
cyberwombat

Reputation: 40153

I see two options.

One is do specify which headers you want in fast-csv and discard the rest. This approach will return an object which may suit your needs or you can then turn that into an array afterwards.

const csv = require('fast-csv')

const CSV_STRING = 'a,b,c\n' +
                     'a1,b1,c1\n' +
                     'a2,b2,c2\n'

let filtered = []
csv
  .fromString(CSV_STRING, { headers: ['column_1', 'column_2'], renameHeaders: true, discardUnmappedColumns: true }) // I give arbitrary names to the first two columns - use whatever make sense
  // .fromString(CSV_STRING, { headers: ['column_1', undefined, 'column_3'], discardUnmappedColumns: true }) // I could use undefined if I wanted to say skip column 2 and just want 1 and 3
  .on('data', function (data) {
    // console.log([data.column_1, data.column_2])
    filtered.push([data.column_1, data.column_2]) // or you can push to an array
  })
  .on('end', function () {
    console.log('done')
    console.log(filtered)
  })

The other is to return as an array (default) and filter what you need using the transform method

const csv = require('fast-csv')

const CSV_STRING = 'a,b,c\n' +
                     'a1,b1,c1\n' +
                     'a2,b2,c2\n'

csv
  .fromString(CSV_STRING)
  .transform(function (data) {
    return [data[0], data[1]]
  })
  .on('data', function (data) {
    console.log(data)
  })
  .on('end', function () {
    console.log('done')
  })

Upvotes: 1

Related Questions