Bun/NodeJS - Example of using json-2-csv package and emptyFieldValue option

Β·

1 min read

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!")
})

Output