Node.js fs-extra outputJson() Function
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().
- 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:
Project Structure: The project structure will look like this.