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:
- The module can be installed by using the following command:
npm install fs-extra
-
After the installation of the module you can check the version of the installed module by using this command:
npm ls fs-extra
-
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');
-
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
import fs from "fs-extra"
const file = "file.json" ;
fs.readJson(file, (err, object) => {
if (err) return console.log(err);
console.log(object);
});
|
Output:
Example 2:
index.js
import fs from "fs-extra"
const file = "file.json" ;
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...