5

I'm looking at the NPM package csv-parser that parses csv files to JSON. Based on the example provided, you can read a csv file row by row in the following manner:

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (rowData) => console.log(rowData))
  .on('end', () => { console.log("done reading the file") });

Is there any way I can only return the header values of the CSV file instead?

blankface
  • 5,757
  • 19
  • 67
  • 114

3 Answers3

5

You can use headers event

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('headers', (headers) => {
    console.log(`First header: ${headers[0]}`)
  })

From official docs

https://www.npmjs.com/package/csv-parser#headers-1

enter image description here

Matt_Bro
  • 14,062
  • 2
  • 28
  • 41
DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
3

In addition to this answer https://stackoverflow.com/a/66756097/12285424, if you only need to read headers, you should destroy the read stream in order to stop it from parsing the entire file, e.g:

let myHeaders;
let readStream = fs.createReadStream('data.csv');
readStream
  .pipe(csv())
  .on('headers', (headers) => {
    console.log(`First header: ${headers[0]}`)
    myHeaders = headers;
    readStream.destroy();
  })
2

https://github.com/mafintosh/csv-parser#headers-1

Emitted after the header row is parsed. The first parameter of the event callback is an Array[String] containing the header names.

use .on('headers', (headers) event

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('headers', (headers) => {
    console.log(headers)
  })
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107