node.jsfast-csv

write headers in csv file with fast-csv


I am trying to add headers to my csv file using fast-csv

my csv file :

"nina", 24

"sarah", 25

const csv = require('fast-csv')

const ws = fs.createWriteStream("/file.csv") ;
 csv.write({headers : ['name', 'age']} )
 .pipe(ws) ;

but it doesn't work how can I modify this code to add my headers?


Solution

  • According to the docs here: https://c2fo.github.io/fast-csv/docs/formatting/methods#write, the first parameter to .write is the data rows that you want to write, but you have the options as the first parameter.

    Try something like this:

    const rows = [[“nina”, 24], [“sarah”,25]];
    csv.write(rows, {headers : ['name', 'age']} )
     .pipe(ws);