Node.js fs-extra outputJson() Function
Last Updated :
12 Aug, 2021
The outputJson() function writes an object to the JSON file. If the user wants to write data onto a file that doesn’t exist it will be created by the function itself. outputJSON() can also be used in place of outputJson().
Syntax:
fs.outputJson(file,object,options,callback)
or
fs.outputJSON(file,object,options,callback)
Parameters:
- file: It is a string that contains the file path.
- object: It is an object that will be written onto the file.
- options: It is an object that contains optional parameters that can be passed into the function.
1. spaces: It is a number specifying the number of spaces to indent or a string used for indentation like ‘\t’ for tab.
2. EOL: It is the end of line character. By default, the character is ‘\n’.
3. replacer: This can be a function or an array used as a selected filter for the stringify. If the value is empty or null then all properties of an object are included in a string.
4. It also accepts the fs.writeFile() options.
- callback: It will be called after the task is completed by the function. It will either result in an error or success. 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
-
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" ;
const object = {
name: "GeeksforGeeks" ,
type: "website" ,
};
fs.outputJSON(file, object, err => {
if (err) return console.log(err);
console.log( "Object written to given JSON file" );
});
|
Output:
Example 2:
index.js
import fs from "fs-extra"
const file = "dir/file.json" ;
const object = {
name: "GeeksforGeeks" ,
type: "website" ,
};
const options = {
spaces: 2,
EOL: "\n" ,
};
fs.outputJSON(file, object, options)
.then(() => console.log( "File created and object written successfully" ))
. catch ((e) => console.log(e));
|
Output:
Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/outputJson.md
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...