How to read and write JSON file using Node.js ?

28 Jan, 2020
Node.js is an open source and cross-platform runtime environment for executing JavaScript code outside of the browser. It is widely used in developing APIs and microservices from small to large companies.
JSON or JavaScript Object Notation is a light weight, text-based data interchange format. Like XML, it is one of the way of exchanging information between applications. This format of data is widely used by web applications/APIs to communicate with each other.
Reading a JSON file:
Method 1: Using require method: The simplest method to read a JSON file is to require it in a node.js file using require() method.Syntax:const data = require('path/to/file/filename');Example: Create a users.json file in the same directory where index.js file present. Add following data to the json file.users.json file:[  {     "name": "John",     "age": 21,    "language": ["JavaScript", "PHP", "Python"]   },  {     "name": "Smith",     "age": 25,     "language": ["PHP", "Go", "JavaScript"]   }]Now, add the following code to your index.js file.index.js file:// Requiring users fileconst users = require("./users");  console.log(users);Now, run the file using the command:node index.jsOutput:
Syntax:
const data = require('path/to/file/filename');
Example: Create a users.json file in the same directory where index.js file present. Add following data to the json file.
users.json file:
[  {     "name": "John",     "age": 21,    "language": ["JavaScript", "PHP", "Python"]   },  {     "name": "Smith",     "age": 25,     "language": ["PHP", "Go", "JavaScript"]   }]
Now, add the following code to your index.js file.
index.js file:
// Requiring users fileconst users = require("./users");  console.log(users);
Now, run the file using the command:
node index.js
Output:
Method 2: Using the fs module: We can also use node.js fs module to read a file. The fs module returns a file content in string format so we need to convert it into JSON format by using JSON.parse() in-built method.Add the following code into your index.js file:index.js file:const fs = require("fs");   // Read users.json filefs.readFile("users.json", function(err, data) {          // Check for errors    if (err) throw err;       // Converting to JSON    const users = JSON.parse(data);          console.log(users); // Print users });Now run the file again and you’ll see an output like this:Output:
const fs = require("fs");   // Read users.json filefs.readFile("users.json", function(err, data) {          // Check for errors    if (err) throw err;       // Converting to JSON    const users = JSON.parse(data);          console.log(users); // Print users });
Now run the file again and you’ll see an output like this:Output:
Writing to a JSON file: We can write data into a JSON file by using the node.js fs module. We can use writeFile method to write data into a file.
Syntax:
fs.writeFile("filename", data, callback);
Example: We will add a new user to the existing JSON file, we have created in the previous example. This task will be completed in three steps:
Read the file using one of the above methods.
Add the data using .push() method.
Write the new data to the file using JSON.stringify() method to convert data into string.
const fs = require("fs");  // STEP 1: Reading JSON fileconst users = require("./users");   // Defining new userlet user = {    name: "New User",    age: 30,    language: ["PHP", "Go", "JavaScript"]};   // STEP 2: Adding new data to users objectusers.push(user);   // STEP 3: Writing to a filefs.writeFile("users.json", JSON.stringify(users), err => {         // Checking for errors    if (err) throw err;        console.log("Done writing"); // Success});
Run the file again and you will see a message into the console:
Now check your users.json file it will looks something like below:
Node.js-Misc
Picked
Technical Scripter 2019
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
JWT Authentication with Node.js
Installation of Node.js on Windows
How to use an ES6 import in Node.js?
Difference between dependencies, devDependencies and peerDependencies
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React