Skip to content

Commit 2799903

Browse files
committed
(Closes #45) jsonfile: strip BOM
1 parent 99e8d32 commit 2799903

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

index.js

+10
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ function readFile (file, options, callback) {
2424
fs.readFile(file, options, function (err, data) {
2525
if (err) return callback(err)
2626

27+
data = stripBom(data)
28+
2729
var obj
2830
try {
2931
obj = JSON.parse(data, options ? options.reviver : null)
@@ -57,6 +59,7 @@ function readFileSync (file, options) {
5759
}
5860

5961
var content = fs.readFileSync(file, options)
62+
content = stripBom(content)
6063

6164
try {
6265
return JSON.parse(content, options.reviver)
@@ -107,6 +110,13 @@ function writeFileSync (file, obj, options) {
107110
return fs.writeFileSync(file, str, options)
108111
}
109112

113+
function stripBom (content) {
114+
// we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
115+
if (Buffer.isBuffer(content)) content = content.toString('utf8')
116+
content = content.replace(/^\uFEFF/, '')
117+
return content
118+
}
119+
110120
var jsonfile = {
111121
spaces: null,
112122
readFile: readFile,

test/read-file-sync.test.js

+10
Original file line numberDiff line numberDiff line change
@@ -162,4 +162,14 @@ describe('+ readFileSync()', function () {
162162
assert.deepEqual(dataOut, dataIn)
163163
})
164164
})
165+
166+
describe('> w/ BOM', function () {
167+
it('should properly parse', function () {
168+
var file = path.join(TEST_DIR, 'file-bom.json')
169+
var obj = { name: 'JP' }
170+
fs.writeFileSync(file, '\uFEFF' + JSON.stringify(obj))
171+
var data = jf.readFileSync(file)
172+
assert.deepEqual(obj, data)
173+
})
174+
})
165175
})

test/read-file.test.js

+13
Original file line numberDiff line numberDiff line change
@@ -231,4 +231,17 @@ describe('+ readFile()', function () {
231231
})
232232
})
233233
})
234+
235+
describe('> w/ BOM', function () {
236+
it('should properly parse', function (done) {
237+
var file = path.join(TEST_DIR, 'file-bom.json')
238+
var obj = { name: 'JP' }
239+
fs.writeFileSync(file, '\uFEFF' + JSON.stringify(obj))
240+
jf.readFile(file, function (err, data) {
241+
assert.ifError(err)
242+
assert.deepEqual(obj, data)
243+
done()
244+
})
245+
})
246+
})
234247
})

0 commit comments

Comments
 (0)