Skip to main content

Command Palette

Search for a command to run...

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

Published
1 min read
Bun/NodeJS - Example of using json-2-csv package and emptyFieldValue option
L

I am a developer from Vietnam.

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

More from this blog

Vietnamese / Ja / En  🧑‍💻 blog

155 posts

Vietnamese developer 🧑‍💻