Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Node.js fs-extra readJson() Function

  • Last Updated : 08 Mar, 2021

The readJson() function reads a JSON file and then parses it into an object. If the file does not exist it will throw an error. readJSON() can also be used in place of readJson().

Syntax:

fs.readJson(file,options,callback)

or

fs.readJSON(file,options,callback)

Parameters:

  • file: It is a string that contains the file path.
  • options: It is an optional parameter that can be passed into the function.The options are same as that of fs.readFile() options.
  • callback: It will be called after the task is completed by the function. It will either result in an error or the object which has the JSON data stored in the file. Promises can also be used in place of the callback function.

Return value: It does not return anything.

Follow the steps to implement the function:

  1. The module can be installed by using the following command:
    npm install fs-extra
  2. After the installation of the module you can check the version of the installed module by using this command:

    npm ls fs-extra

  3. 3. Create a file with the name index.js and require the fs-extra module in the file using the following command:

    const fs = require('fs-extra');
  4. To run the file write the following command in the terminal:

    node index.js

Project Structure: The project structure will look like this.

Example 1: 

index.js




// Requiring module
import fs from "fs-extra"
  
// File path
const file = "file.json";
  
// Function call
// Using callback function
fs.readJson(file, (err, object) => {
  if (err) return console.log(err);
  console.log(object);
});

Output:

Example 2:

index.js




// Requiring module
import fs from "fs-extra"
  
// File path
const file = "file.json";
  
// Function call
// Using Promises
// readJSON can be
// used in place of
// readJson as well
fs.readJSON(file)
  .then((object) => console.log(object))
  .catch((e) => console.log(e));

Output:

Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/readJson.md


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!