How to read and write JSON Files with Node.js?
Tags: node, javascript, json
Published: 2021-05-17 11:59:34

---
title: How to read and write JSON Files with Node.js?
published: true
date: 2021-03-02 00:00:00 UTC
tags: node, javascript, JSON
canonical_url: https://www.mariokandut.com/how-to-read-and-write-json-files-with-node-js/
---

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.

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#interacting-with-files)Interacting with files

Files can be accessed in Node.js with the native module `fs` to watch, read and write files. For a fresher on the fs module, have a look at this article [Node file system](https://www.mariokandut.com/what-is-the-node-fs-file-system-module/). 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 startup, besides these use cases and in general async versions should be used.

To read and write files async the native fs module provides the functions `fs.readFile` and `fs.writeFile`.

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#read-a-json-file)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`.

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#read-a-json-file-with-fsreadfile)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": "hello@mario.com"
```

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.

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#write-to-a-json-file-with-fswritefile)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: 'hello@mario.com',
};
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: 'hello@mario.com',
};

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`.

JSON is one of the most common types of data you’ll work with in Node, and being able to read and write JSON files is very useful. You’ve learned how to use fs.readFile and fs.writeFile to asynchronously work with the filesystem, as well as how to parse data to and from JSON format, and catch errors from JSON.parse.

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#tldr)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](https://www.twitter.com/mariokandut)**.

If you want to know more about **[Node](https://www.mariokandut.com/tags/node)**, have a look at these [Node Tutorials](https://www.mariokandut.com/tags/node).

[💰: $100 (credits) for you to start your cloud journey with DigitalOcean!](https://m.do.co/c/29f238135b61)

### [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#references-and-big-thanks)References (and Big thanks):

[Node FS](https://nodejs.org/api/fs.html), [HeyNode](https://heynode.com/tutorial/readwrite-json-files-nodejs), [MDN JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON)