From 5ce59a345ee7eba08eb544a89689c14da163f149 Mon Sep 17 00:00:00 2001 From: jkirkpatrick24 Date: Sat, 9 Jan 2021 12:04:48 -0800 Subject: [PATCH] fix: support parsing buffers --- index.js | 4 ++++ test.js | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/index.js b/index.js index 94258b7..6d21eb0 100755 --- a/index.js +++ b/index.js @@ -17,6 +17,10 @@ function parse (text, reviver, options) { const protoAction = options.protoAction || 'error' const constructorAction = options.constructorAction || 'error' + if (Buffer.isBuffer(text)) { + text = text.toString() + } + // BOM checker if (text && text.charCodeAt(0) === 0xFEFF) { text = text.slice(1) diff --git a/test.js b/test.js index db03cb2..525b870 100644 --- a/test.js +++ b/test.js @@ -36,6 +36,14 @@ test('parse', t => { t.end() }) + t.test('parses buffer', t => { + t.strictEqual( + j.parse(Buffer.from('"X"')), + JSON.parse(Buffer.from('"X"')) + ) + t.end() + }) + t.test('parses object string (reviver)', t => { const reviver = (key, value) => { return typeof value === 'number' ? value + 1 : value @@ -373,3 +381,13 @@ test('parse string with BOM', t => { t.deepEqual(j.parse(buffer.toString()), theJson) t.end() }) + +test('parse buffer with BOM', t => { + const theJson = { hello: 'world' } + const buffer = Buffer.concat([ + Buffer.from([239, 187, 191]), // the utf8 BOM + Buffer.from(JSON.stringify(theJson)) + ]) + t.deepEqual(j.parse(buffer), theJson) + t.end() +})