Open In App

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().

Syntax:



fs.outputJson(file,object,options,callback)

or

fs.outputJSON(file,object,options,callback)

Parameters:



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.

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. 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"
  
// This file already
// exists so function
// will write onto the file
const file = "file.json";
  
// Object
// This will be
// written onto
// the file
const object = {
  name: "GeeksforGeeks",
  type: "website",
};
  
// Function call
// Using callback function
fs.outputJSON(file, object, err => {
  if(err) return console.log(err);
  console.log("Object written to given JSON file");
});

Output:

Example 2:




// Requiring module
import fs from "fs-extra"
  
// This file does not
// exists so function
// will create file
// and write data onto it
const file = "dir/file.json";
  
// Object
// This will be
// written onto
// the file
const object = {
  name: "GeeksforGeeks",
  type: "website",
};
  
// Additional options
const options = {
  spaces: 2,
  EOL: "\n",
};
  
// Function call
// Using Promises
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


Article Tags :