index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. let _fs
  2. try {
  3. _fs = require('graceful-fs')
  4. } catch (_) {
  5. _fs = require('fs')
  6. }
  7. const universalify = require('universalify')
  8. const { stringify, stripBom } = require('./utils')
  9. async function _readFile (file, options = {}) {
  10. if (typeof options === 'string') {
  11. options = { encoding: options }
  12. }
  13. const fs = options.fs || _fs
  14. const shouldThrow = 'throws' in options ? options.throws : true
  15. let data = await universalify.fromCallback(fs.readFile)(file, options)
  16. data = stripBom(data)
  17. let obj
  18. try {
  19. obj = JSON.parse(data, options ? options.reviver : null)
  20. } catch (err) {
  21. if (shouldThrow) {
  22. err.message = `${file}: ${err.message}`
  23. throw err
  24. } else {
  25. return null
  26. }
  27. }
  28. return obj
  29. }
  30. const readFile = universalify.fromPromise(_readFile)
  31. function readFileSync (file, options = {}) {
  32. if (typeof options === 'string') {
  33. options = { encoding: options }
  34. }
  35. const fs = options.fs || _fs
  36. const shouldThrow = 'throws' in options ? options.throws : true
  37. try {
  38. let content = fs.readFileSync(file, options)
  39. content = stripBom(content)
  40. return JSON.parse(content, options.reviver)
  41. } catch (err) {
  42. if (shouldThrow) {
  43. err.message = `${file}: ${err.message}`
  44. throw err
  45. } else {
  46. return null
  47. }
  48. }
  49. }
  50. async function _writeFile (file, obj, options = {}) {
  51. const fs = options.fs || _fs
  52. const str = stringify(obj, options)
  53. await universalify.fromCallback(fs.writeFile)(file, str, options)
  54. }
  55. const writeFile = universalify.fromPromise(_writeFile)
  56. function writeFileSync (file, obj, options = {}) {
  57. const fs = options.fs || _fs
  58. const str = stringify(obj, options)
  59. // not sure if fs.writeFileSync returns anything, but just in case
  60. return fs.writeFileSync(file, str, options)
  61. }
  62. const jsonfile = {
  63. readFile,
  64. readFileSync,
  65. writeFile,
  66. writeFileSync
  67. }
  68. module.exports = jsonfile