Search code examples
javascriptnode.jscsvcsv-parser

Use csv-parser to only return file headers


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?


Solution

  • 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