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!
Managing PHP Dependencies with Composer
Getting Started with Svelte
Getting Started with Express
How to deploy a PHP app using Docker
How to deploy a MySQL Server using Docker
Getting Started with Sass
Learn how to use v-model with a custom Vue component
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up a Local Web Server using Node.js
