How to read and write JSON Files with Node.js?
© https://nodejs.org/en/

How to read and write JSON Files with Node.js?

Save data between restarts

ByMario Kandut

honey pot logo

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

Using JSON files in your Node.js application can be a useful way to persist data. For example, if you want to store data between a Node server restart, JSON files are a convenient option. Node has some built-in utilities to read and write JSON files.

This article is based on Node v16.14.0.

Interacting with files

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

Files can be accessed in Node.js with the native module fs to watch, read and write files. For a refresher on the fs module, have a look at this article Node file system. FS is a native module, and can be required without installing it. Simply call const fs = require('fs'). You have synchronous and asynchronous versions for some provided functions. The synchronous version blocks execution of other code until they are done interacting (read, write) with the filesystem. An async function will run without blocking other code. Synchronous function have some use cases, like loading configs on the startup, besides these use cases and in general async versions should be used.

JSON is one of the most common types of data, and being able to read and write JSON files in a Node.js environment is very useful. To read and write files async the native fs module provides the functions fs.readFile and fs.writeFile.

Read a JSON file

The simplest way to read a JSON file is to require it, like so:

const jsonFile = require('./config.json');

There are some things to consider, when using this approach. The file will be only read once, and it will be cached. This means, when requiring it again, the cached version will be returned. This is fine for static data, but not for data that changes dynamically. For dynamic data we have to use fs.readFile.

Read a JSON file with fs.readFile

Let's say we have a json file of a customer, and we want to print the customer address. We would have to read the JSON data from the file and then parse it to a JavaScript object.

customer.json:

"firstName": "Mario",
"address": "Null Island",
"email": "[email protected]"

To read the file we have to provide the relative file path, format (optional), and a callback function to fs.readFile.

const fs = require('fs');
fs.readFile('./customer.json', 'utf8', (err, data) => {
  if (err) {
    console.log('File read failed:', err);
    return;
  }
  console.log('File data:', data);
});

Now we have the contents of the file as a JSON string. We can parse the JSON string with the global helper method JSON.parse(). If parsing the JSON throws an error, we have to handle it in a catch block.

const fs = require('fs');
fs.readFile('./customer.json', 'utf8', (err, data) => {
  if (err) {
    console.log('Error reading file:', err);
    return;
  }
  try {
    const customer = JSON.parse(data);
    console.log('Customer address is:', customer.address);
  } catch (err) {
    console.log('Error parsing JSON:', err);
  }
});

Now we have an object representation of the data in the JSON file. We can also read the data synchronously with fs.readFilySync. fs.readFileSync does not take a callback function and returns the data direct after reading the file. Though it blocks all other code.

Write to a JSON file with fs.writeFile

Writing is similar to reading a JSON file, the async function fs.writeFile writes data to the file system.

Let's say we want to write a JavaScript object to a JSON file. Similar to parsing data into an object when reading, we have to transform data into a string to be able to write it to a file. We have to create a JSON string of the javascript object with the global helper method JSON.stringify. This JSON string representation of a JavaScript object then can be written to a file.

We have to create a data object and turn it into a string.

const customer = {
  firstName: 'Mario',
  address: 'Null Island',
  email: '[email protected]',
};
const jsonString = JSON.stringify(customer);

Once the data is stringified, we can write it to a file with fs.writeFile.

const fs = require('fs');
const customer = {
  firstName: 'Mario',
  address: 'Null Island',
  email: '[email protected]',
};

const jsonString = JSON.stringify(customer);

fs.writeFile('./newCustomer.json', jsonString, err => {
  if (err) {
    console.log('Error writing file', err);
  } else {
    console.log('Successfully wrote file');
  }
});

That’s it! Once the callback runs, the file has been written to disk. Files can also be written synchronously with fs.writeFileSync.

TL;DR

  • Use fs.readFile to read files async
  • Use fs.writeFile to write files async
  • Use async methods to avoid code execution blocking.

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

References (and Big thanks):

Node FS, HeyNode, MDN JSON

More node articles:

Getting started with Webpack

How to list/debug npm packages?

How to specify a Node.js version

How to create a web server in Node.js

How to dynamically load ESM in CJS

How to convert a CJS module to an ESM

How to create a CJS module

How to stream to an HTTP response

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑