How to Read and Write JSON to a File in Node
Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTimport { 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:
JAVASCRIPTimport { 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!
- Getting Started with TypeScript
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React