In an earlier article, we looked at converting a CSV file to a JSON array in a Node.js application. This article is the continuation of the previous article where you'll how to convert a JSON array into a CSV file.

To do the JSON to CSV conversion, we'll be using the json-2-csv module from Node Package Manager (NPM). This package converts an array of JSON documents into a CSV string. It automatically generates column headings based on the keys of the JSON documents. Nested documents will have a '.' appended between the keys.

Create an Application

Create a new project directory in your local file system and switch to this location in your terminal. Now type the following command to initialize a Node.js application:

$ npm init -y

The above command will create a package.json file in the root directory. Next, install the only required dependency — json-2-csv by typing the following command:

$ npm install json-2-csv --save

Convert JSON to CSV

To convert a JSON array to a CSV file, create a new file named app.js in your project root directory:

$ touch app.js

If the touch command is not available, just create the file manually. Open the app.js file in your favorite editor and add the following code:

app.js

// require json-2-csv module
const converter = require('json-2-csv')

// declare a JSON array
const todos = [
  {
    id: 1,
    title: 'delectus aut autem',
    completed: false
  },
  {
    id: 2,
    title: 'quis ut nam facilis et officia qui',
    completed: false
  },
  {
    id: 3,
    title: 'fugiat veniam minus',
    completed: false
  }
]

// convert JSON array to CSV string
converter.json2csv(todos, (err, csv) => {
  if (err) {
    throw err
  }

  // print CSV string
  console.log(csv)
})

The above example is very much self-explanatory. It will print out the following CSV on the console:

id,title,completed
1,delectus aut autem,false
2,quis ut nam facilis et officia qui,false
3,fugiat veniam minus,false

Write CSV to File

To write the output CSV string to a file for further processing, just use the following JavaScript code:

// convert JSON array to CSV string
converter.json2csv(todos, (err, csv) => {
  if (err) {
    throw err
  }

  // print CSV string
  console.log(csv)

  // write CSV to a file
  fs.writeFileSync('todos.csv', csv)
})

Readthis guide to learn more about how to write a file in a Node.js application.

Read JSON from File

If your JSON array is stored in a file, you can easily read it by using the native fs module and then perform the conversion as shown below:

app-file.js

// require json-2-csv module
const converter = require('json-2-csv')
const fs = require('fs')

// read JSON from a file
const todos = JSON.parse(fs.readFileSync('todos.json'))

// convert JSON array to CSV string
converter.json2csv(todos, (err, csv) => {
  if (err) {
    throw err
  }

  // print CSV string
  console.log(csv)

  // write CSV to a file
  fs.writeFileSync('todos.csv', csv)
})

Promises

Prefer to use promises? No problem! The json-2-csv module provides a special method called json2csvAsync() that returns a promise instead of taking a callback as an argument.

Here is an example:

app-promise.js

// require json-2-csv module
const converter = require('json-2-csv')
const fs = require('fs')

// read JSON from a file
const todos = JSON.parse(fs.readFileSync('todos.json'))

// convert JSON array to CSV string
converter
  .json2csvAsync(todos)
  .then(csv => {
    // print CSV string
    console.log(csv)

    // write CSV to a file
    fs.writeFileSync('todos.csv', csv)
  })
  .catch(err => console.log(err))

Async-Await

The json-2-csv module also supports async-await syntax. Here is an example:

app-async.js

// require json-2-csv module
const converter = require('json-2-csv')
const fs = require('fs')

// read JSON from a file
const todos = JSON.parse(fs.readFileSync('todos.json'))

// convert JSON array to CSV string
;(async () => {
  try {
    const csv = await converter.json2csvAsync(todos)

    // print CSV string
    console.log(csv)

    // write CSV to a file
    fs.writeFileSync('todos.csv', csv)
  } catch (err) {
    console.log(err)
  }
})()

Source Code: Download the complete source code from GitHub available under MIT license.

Conclusion

We looked at how to use the json-2-csv module to convert a JSON array into a CSV file in a Node.js Application.

Take a look at the json-2-csv module documentation to learn more about all the available options. You can also use it to convert the CSV string back into the original array of JSON documents.

Read Next: How to convert CSV to JSON in Node.js

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.