Convert JSON to CSV with Node.js using readFileSync

 I have to convert some JSON format files to CSV format to read or access them properly from MS-Excel.

You are able to see I split my VS-code screen and on the left side, you can see the code that I have used for conversion, and on the right part, you will get the JSON file that we want to convert it.
In the terminal below, you can view the logs as “CSV file created successfully”.

So let’s go step-by-step to get the same result as mine.

There are a few pre-requisites, they are as follows:
a. Nodejs installed on your local machine — https://nodejs.org/

  1. Install packages “json2csv” using the following command: $ npm install json2csv
npm install json2csv

Additionally, you don’t need to install any packages specifically for the built-in fs (file-system) module since it is a part of Node.js and comes pre-installed with it.
You can directly use it like this as shown below:

const json2csv = require('json2csv').parse;
const fs = require('fs');

The first line imports the parse function from the json2csv module and assigns it to the variable json2csv.
This second line imports the built-in Node.js module fs (file system).
assigns it to the variable fs.
The fs module provides functions for interacting with the file system.

const data = fs.readFileSync('./Data-Files/Florida/LEHIGH REGIONAL MEDICAL CENTER.json', 'utf-8');

Here in the above line of code, I have used my JSON file and this line reads the contents of the file located in the quotes and assigns the data to the ‘const data’. The ‘utf-8’ argument specifies the encoding of the file.

Parsing the JSON data

This line parses the JSON data stored in the data variable and converts it into a JavaScript object.
The resulting object is assigned to the variable jsonData.

Converting data into CSV

This line calls the json2csv function,
This json2csv function(imported from the json2csv module) with the HIMCPT property of the jsonData object as an argument.
It converts the data into CSV format and assigns the result to the variable as ‘const csv’.

fs.writeFile(‘./Data-Files/Florida/LEHIGH REGIONAL MEDICAL CENTER.csv’, csv, function(err) {

This line calls the writeFile function from the fs module. It takes three arguments:
a. The file path where the CSV file will be created (‘./Data-Files/Florida/LEHIGH REGIONAL MEDICAL CENTER.csv’),

b. The data to be written to the file (csv variable), and

c. A callback function to handle any errors that occur during the write operation.

if (err) throw err;

This line checks if an error occurred during the write operation.
If an error is present, it is thrown, which means the program execution will stop and the error will be displayed in the terminal.

Full code in one place

Comments

Popular posts from this blog

Validating Date of Birth in Angular Reactive Form: Best Practices and Examples

Understanding Node.js Event Emitter: A Powerful Event Handling Mechanism