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

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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    [
      
        "name": "John"
        "age": 21,
        "language": ["JavaScript", "PHP", "Python"
      },
      {
         "name": "Smith",
         "age": 25,
         "language": ["PHP", "Go", "JavaScript"
      }
    ]

    chevron_right

    
    

    Now, add the following code to your index.js file.

    index.js file:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Requiring users file
    const users = require("./users");
      
    console.log(users);

    chevron_right

    
    

    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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    const fs = require("fs");
       
    // Read users.json file
    fs.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 
    });

    chevron_right

    
    

    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.
filter_none

edit
close

play_arrow

link
brightness_4
code

const fs = require("fs");
  
// STEP 1: Reading JSON file
const users = require("./users");
   
// Defining new user
let user = {
    name: "New User",
    age: 30,
    language: ["PHP", "Go", "JavaScript"]
};
   
// STEP 2: Adding new data to users object
users.push(user);
   
// STEP 3: Writing to a file
fs.writeFile("users.json", JSON.stringify(users), err => {
     
    // Checking for errors
    if (err) throw err; 
   
    console.log("Done writing"); // Success
});

chevron_right


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:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.