How to Read and Write JSON to a File in Node

Updated onbyAlan Morel
How to Read and Write JSON to a File in Node

JSON is the most popular data format used in JavaScript because it is easy to read and write.

Sometimes you want to store data in a file and you want to be able to read it back later, rather than keeping the data in memory.

In this post, we'll learn how to read and write JSON to a file in Node.

How to Write JSON to a File

Let's start out with an example object to write:

JAVASCRIPT
const object = { name: "John Doe", age: 30 };

To write this file to the disk, we'll need to import the fs module, then use JSON.stringify to turn this object into a string:

JAVASCRIPT
import { promises as fs } from "fs"; const object = { name: "John Doe", age: 30 }; const json = JSON.stringify(object); const path = "person.json"; await fs.writeFile(path, json);

This uses the async/await pattern to asynchronously write the file to the disk using promises rather than callback functions.

As long as the path is valid and your permissions are set, this will work and you will get your JSON file written to the disk.

How to Read JSON from a File

Similarly to when writing, when we want to read this file, we'll need to import the fs module and use JSON.parse to turn the string back into an object:

JAVASCRIPT
import { promises as fs } from "fs"; const path = "person.json"; const json = await fs.readFile(path); const object = JSON.parse(json); console.log(object);
BASH
{ "name": "John Doe", "age": 30 }

Again, we are taking advantage of promises to asynchronously read the file from the disk, then using await to wait for the result.

As you can see, it is extremely easy to read and write a file in Node.

Conclusion

In this post, we learned how to write and read JSON to a file in Node.

All you need to do is import the fs module and use the promises version of the writeFile and readFile methods.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.