readJson() function in fs-extra - NodeJS

Node.jsServer Side ProgrammingProgramming

readJson() method reads a JSON object and then parses it into an object.

Syntax

readJson(file [, options] [, callback])

Parameters

  • file – String parameter which will contain name and location of the file holding the JSON.

  • options – The 'outputFile' function supports the following options −

    • encoding – Default 'null'.

    • flag – Default 'r'. The flag 'r' opens a file for reading and an exception will occur if file does not exist.

    • signal – allows aborting an ongoing output file function

  • callback – This function will give a callback if any error occurs.

Example 1

  • Check that fs-extra is installed before proceeding; if not, install fs-exra.

  • You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
  • Create an asyncReadJsonExample.js and copy-paste the following code snippet into that file.

  • Now, run the following command to run the following code snippet.

node asyncReadJsonExample.js

Code Snippet

const fs = require('fs-extra')

// Reading JSON with a callback:
fs.readJson('./package.json', (err, packageObj) => {
   if (err) console.error(err)
      console.log(packageObj.version) // => 1.0.0
})

// Reading JSON Promises:
fs.readJson('./package.json')
.then(packageObj => {
   console.log(packageObj.version) // => 1.0.0
})
.catch(err => {
   console.error(err)
})

// Reading JSON withasync/await:
async function asyncReadJsonExample () {
   try {
      const packageObj = await fs.readJson('./package.json')
      console.log(packageObj.version) // => 1.0.0
   } catch (err) {
      console.error(err)
   }
}

asyncReadJsonExample()

Output

C:\Users\tutorialsPoint\> node asyncReadJsonExample.js
1.0.0
1.0.0
1.0.0

Introduction to readJsonSync()

This method reads JSON and parses it into an object.

Syntax

readJsonSync(file, [, options])

Parameters

  • file – This is a string paramter which will hold the location of the file.

  • options – The 'outputFile' function supports the following options −

    • encoding – Default 'null'.

    • flag – Default 'r'. The flag 'r' opens a file for reading and an exception will occur if file does not exist.

Example

  • Check that fs-extra is installed before proceeding; if not, install fs-exra.

  • You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
  • Create a readJsonSyncExample.js and copy-paste the following code snippet into that file.

  • Now, run the following command to run the following code snippet.

node readJsonSyncExample.js

Code Snippet

const fs = require('fs-extra')

const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version) // => 1.0.0

Output

C:\Users\tutorialsPoint\> node readJsonSyncExample.js
1.0.0
raja
Updated on 28-Apr-2021 06:44:41

Advertisements