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!
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
How to deploy a Deno app using Docker
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Using Push.js to Display Web Browser Notifications
Getting Started with React
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
Getting Started with Moon.js
