Open In App

Node.js fs-extra readJson() Function

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:



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: 




// 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:




// 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


Article Tags :