Photo by GΓΆran Eidens on Unsplash
Bun/NodeJS - Example of using json-2-csv package and emptyFieldValue option
Example
import fs from 'fs'
import { json2csv } from 'json-2-csv'
/**
* Example of using 3rd party library json-2-csv.
* json-2-csv: {@link https://www.npmjs.com/package/json-2-csv}
*/
const rows = [
{
name: 'Sato',
age: 3,
weight: 14.9,
note: 'a baby',
updatedAt: '2024-01-01T00:00:00.000Z',
},
{
name: 'Jack',
age: 4,
weight: 15.333333333333334,
note: '',
},
{
name: 'Minh Tue',
age: 5,
weight: '(not set π)',
value4: 'mobile',
},
]
const csv = json2csv(rows, {
/**
* Value that, if specified, will be substituted in for field values
* that are undefined, null, or an empty string
*/
emptyFieldValue: '-',
})
console.log('π ~ csv:', csv)
/**
* bun src/test-json-2-csv.ts
*/
fs.writeFile('name.csv', csv, 'utf8', err => {
if (err !== null) {
console.error('π¨ CSV file writing error: ', err)
return
}
console.info("π§ It's saved!")
})