Write objects to a CSV file with createObjectCsvWriter
masterUse createObjectCsvWriter to convert an array of objects into a CSV file. You can define a header with both an id (the key in your object) and a title (the column name in the CSV). If you provide only strings in the header array, no header line will be written to the file.
To write multiple batches of records to the same file, you must await the promise returned by writeRecords before calling it again to ensure data integrity.
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createObjectCsvWriter({
path: 'path/to/file.csv',
header: [
{id: 'name', title: 'NAME'},
{id: 'lang', title: 'LANGUAGE'}
]
});
const records = [
{name: 'Bob', lang: 'French, English'},
{name: 'Mary', lang: 'English'}
];
csvWriter.writeRecords(records)
.then(() => {
console.log('...Done');
});