# How to convert JSON to CSV in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 9, 2020, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-convert-json-to-csv

> A complete guide to learning how to convert a JSON array to a CSV (Comma-Separated Values) file using Node.js.

In an [earlier article](https://attacomsian.com/blog/nodejs-convert-csv-to-json), 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](https://www.npmjs.com/package/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:

```bash
$ npm init -y
```

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

```bash
$ 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:

```bash
$ 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:

<p class="file-desc"><span>app.js</span></p>

```javascript
// 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:

```csv
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:

```javascript
// 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)
})
```

Read[this guide](https://attacomsian.com/blog/reading-writing-files-nodejs#writing-to-files) 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:

<p class="file-desc"><span>app-file.js</span></p>

```javascript
// 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](https://attacomsian.com/blog/promises-javascript)? 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:

<p class="file-desc"><span>app-promise.js</span></p>

```javascript
// 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](https://attacomsian.com/blog/async-await-javascript) syntax. Here is an example:

<p class="file-desc"><span>app-async.js</span></p>

```javascript
// 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](https://github.com/attacomsian/code-examples/tree/master/nodejs/json-to-csv) 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](https://github.com/mrodrig/json-2-csv) 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](https://attacomsian.com/blog/nodejs-convert-csv-to-json)
