3 _fs = require('graceful-fs')
8 function readFile (file, options, callback) {
9 if (callback == null) {
14 if (typeof options === 'string') {
15 options = {encoding: options}
18 options = options || {}
19 var fs = options.fs || _fs
21 var shouldThrow = true
22 // DO NOT USE 'passParsingErrors' THE NAME WILL CHANGE!!!, use 'throws' instead
23 if ('passParsingErrors' in options) {
24 shouldThrow = options.passParsingErrors
25 } else if ('throws' in options) {
26 shouldThrow = options.throws
29 fs.readFile(file, options, function (err, data) {
30 if (err) return callback(err)
36 obj = JSON.parse(data, options ? options.reviver : null)
39 err2.message = file + ': ' + err2.message
42 return callback(null, null)
50 function readFileSync (file, options) {
51 options = options || {}
52 if (typeof options === 'string') {
53 options = {encoding: options}
56 var fs = options.fs || _fs
58 var shouldThrow = true
59 // DO NOT USE 'passParsingErrors' THE NAME WILL CHANGE!!!, use 'throws' instead
60 if ('passParsingErrors' in options) {
61 shouldThrow = options.passParsingErrors
62 } else if ('throws' in options) {
63 shouldThrow = options.throws
66 var content = fs.readFileSync(file, options)
67 content = stripBom(content)
70 return JSON.parse(content, options.reviver)
73 err.message = file + ': ' + err.message
81 function writeFile (file, obj, options, callback) {
82 if (callback == null) {
86 options = options || {}
87 var fs = options.fs || _fs
89 var spaces = typeof options === 'object' && options !== null
91 ? options.spaces : this.spaces
96 str = JSON.stringify(obj, options ? options.replacer : null, spaces) + '\n'
98 if (callback) return callback(err, null)
101 fs.writeFile(file, str, options, callback)
104 function writeFileSync (file, obj, options) {
105 options = options || {}
106 var fs = options.fs || _fs
108 var spaces = typeof options === 'object' && options !== null
109 ? 'spaces' in options
110 ? options.spaces : this.spaces
113 var str = JSON.stringify(obj, options.replacer, spaces) + '\n'
114 // not sure if fs.writeFileSync returns anything, but just in case
115 return fs.writeFileSync(file, str, options)
118 function stripBom (content) {
119 // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
120 if (Buffer.isBuffer(content)) content = content.toString('utf8')
121 content = content.replace(/^\uFEFF/, '')
128 readFileSync: readFileSync,
129 writeFile: writeFile,
130 writeFileSync: writeFileSync
133 module.exports = jsonfile