index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var fs = require('fs')
  2. function readFile (file, options, callback) {
  3. if (callback == null) {
  4. callback = options
  5. options = {}
  6. }
  7. fs.readFile(file, options, function (err, data) {
  8. if (err) return callback(err)
  9. var obj
  10. try {
  11. obj = JSON.parse(data, options ? options.reviver : null)
  12. } catch (err2) {
  13. err2.message = file + ': ' + err2.message
  14. return callback(err2)
  15. }
  16. callback(null, obj)
  17. })
  18. }
  19. function readFileSync (file, options) {
  20. options = options || {}
  21. if (typeof options === 'string') {
  22. options = {encoding: options}
  23. }
  24. var shouldThrow = 'throws' in options ? options.throws : true
  25. var content = fs.readFileSync(file, options)
  26. try {
  27. return JSON.parse(content, options.reviver)
  28. } catch (err) {
  29. if (shouldThrow) {
  30. err.message = file + ': ' + err.message
  31. throw err
  32. } else {
  33. return null
  34. }
  35. }
  36. }
  37. function writeFile (file, obj, options, callback) {
  38. if (callback == null) {
  39. callback = options
  40. options = {}
  41. }
  42. var spaces = typeof options === 'object' && options !== null
  43. ? 'spaces' in options
  44. ? options.spaces : this.spaces
  45. : this.spaces
  46. var str = ''
  47. try {
  48. str = JSON.stringify(obj, options ? options.replacer : null, spaces) + '\n'
  49. } catch (err) {
  50. if (callback) return callback(err, null)
  51. }
  52. fs.writeFile(file, str, options, callback)
  53. }
  54. function writeFileSync (file, obj, options) {
  55. options = options || {}
  56. var spaces = typeof options === 'object' && options !== null
  57. ? 'spaces' in options
  58. ? options.spaces : this.spaces
  59. : this.spaces
  60. var str = JSON.stringify(obj, options.replacer, spaces) + '\n'
  61. // not sure if fs.writeFileSync returns anything, but just in case
  62. return fs.writeFileSync(file, str, options)
  63. }
  64. var jsonfile = {
  65. spaces: null,
  66. readFile: readFile,
  67. readFileSync: readFileSync,
  68. writeFile: writeFile,
  69. writeFileSync: writeFileSync
  70. }
  71. module.exports = jsonfile