Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

readJson.md 1.2 KiB

3 lat temu
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # readJson(file, [options, callback])
  2. Reads a JSON file and then parses it into an object. `options` are the same
  3. that you'd pass to [`jsonFile.readFile`](https://github.com/jprichardson/node-jsonfile#readfilefilename-options-callback).
  4. **Alias:** `readJSON()`
  5. - `file` `<String>`
  6. - `options` `<Object>`
  7. - `callback` `<Function>`
  8. ## Example:
  9. ```js
  10. const fs = require('fs-extra')
  11. fs.readJson('./package.json', (err, packageObj) => {
  12. if (err) console.error(err)
  13. console.log(packageObj.version) // => 0.1.3
  14. })
  15. // Promise Usage
  16. fs.readJson('./package.json')
  17. .then(packageObj => {
  18. console.log(packageObj.version) // => 0.1.3
  19. })
  20. .catch(err => {
  21. console.error(err)
  22. })
  23. ```
  24. ---
  25. `readJson()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example:
  26. ```js
  27. const fs = require('fs-extra')
  28. const file = '/tmp/some-invalid.json'
  29. const data = '{not valid JSON'
  30. fs.writeFileSync(file, data)
  31. fs.readJson(file, { throws: false }, (err, obj) => {
  32. if (err) console.error(err)
  33. console.log(obj) // => null
  34. })
  35. // Promise Usage
  36. fs.readJson(file, { throws: false })
  37. .then(obj => {
  38. console.log(obj) // => null
  39. })
  40. .catch(err => {
  41. console.error(err) // Not called
  42. })
  43. ```