Skip to content

Commit 5b343f7

Browse files
fix: support parsing buffers (#13)
1 parent 04d5f32 commit 5b343f7

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ function parse (text, reviver, options) {
1717
const protoAction = options.protoAction || 'error'
1818
const constructorAction = options.constructorAction || 'error'
1919

20+
if (Buffer.isBuffer(text)) {
21+
text = text.toString()
22+
}
23+
2024
// BOM checker
2125
if (text && text.charCodeAt(0) === 0xFEFF) {
2226
text = text.slice(1)

test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,14 @@ test('parse', t => {
3636
t.end()
3737
})
3838

39+
t.test('parses buffer', t => {
40+
t.strictEqual(
41+
j.parse(Buffer.from('"X"')),
42+
JSON.parse(Buffer.from('"X"'))
43+
)
44+
t.end()
45+
})
46+
3947
t.test('parses object string (reviver)', t => {
4048
const reviver = (key, value) => {
4149
return typeof value === 'number' ? value + 1 : value
@@ -373,3 +381,13 @@ test('parse string with BOM', t => {
373381
t.deepEqual(j.parse(buffer.toString()), theJson)
374382
t.end()
375383
})
384+
385+
test('parse buffer with BOM', t => {
386+
const theJson = { hello: 'world' }
387+
const buffer = Buffer.concat([
388+
Buffer.from([239, 187, 191]), // the utf8 BOM
389+
Buffer.from(JSON.stringify(theJson))
390+
])
391+
t.deepEqual(j.parse(buffer), theJson)
392+
t.end()
393+
})

0 commit comments

Comments
 (0)