How to Convert JSON to CSV in Node.js

In this article, you'll learn how to create a Node CLI tool to convert a JSON file into a valid CSV file.

JSON has become the most popular way to pass data around on the modern web, with almost universal support between APIs and server applications.

However, the dominant data format in spreadsheet applications like Excel and Google Sheets is CSV, as this format is the tersest and easiest for users to understand and create.

A common function that backend apps will need to perform, therefore, is the conversion of JSON to CSV. In this tutorial, we'll create a CLI script to convert an input JSON file to an output CSV file.

What you'll learn#

  • How to create a CLI script with Node.js

  • How to load a JSON file from the filesystem

  • Writing a method to convert a JSON structure to CSV

  • Writing the CSV file to the filesystem

If you don't need to customize the conversion process, it's quicker to use a third-party package like json-2-csv. At the end of the tutorial, I'll also show you how to use this instead of a custom converter.

Prerequisites#

To get the most out of this article you should be familiar with the basics of Node.js, JavaScript, and async/await.

You'll need a version of Node.js that includes fs.promises and supports async/await and also have NPM installed. I recommend Node v12 LTS which includes NPM 6.

Setting up THE project#

Let's now get started making a Node script that we can use to convert a JSON file to CSV from the command line. First, we'll create the source code directory, json-to-csv. Change into that and run npm init -y so that we're ready to add some NPM packages.

Example JSON file#

Let's now create am example JSON file that we can work with called input.json. I've created a simple data schema with three properties: name, email, and date of birth.