readJson(file, [options, callback])

Reads a JSON file and then parses it into an object. options are the same that you’d pass to jsonFile.readFile.

Alias: readJSON()

  • file <String>
  • options <Object>
  • callback <Function>

Example:

  1. const fs = require('fs-extra')
  2. fs.readJson('./package.json', (err, packageObj) => {
  3. if (err) console.error(err)
  4. console.log(packageObj.version) // => 0.1.3
  5. })
  6. // Promise Usage
  7. fs.readJson('./package.json')
  8. .then(packageObj => {
  9. console.log(packageObj.version) // => 0.1.3
  10. })
  11. .catch(err => {
  12. console.error(err)
  13. })

readJson() can take a throws option set to false and it won’t throw if the JSON is invalid. Example:

  1. const fs = require('fs-extra')
  2. const file = '/tmp/some-invalid.json'
  3. const data = '{not valid JSON'
  4. fs.writeFileSync(file, data)
  5. fs.readJson(file, { throws: false }, (err, obj) => {
  6. if (err) console.error(err)
  7. console.log(obj) // => null
  8. })
  9. // Promise Usage
  10. fs.readJson(file, { throws: false })
  11. .then(obj => {
  12. console.log(obj) // => null
  13. })
  14. .catch(err => {
  15. console.error(err) // Not called
  16. })