Skip to content

Commit 6425e20

Browse files
authored
fix: handle bom in text and json (node-fetch#1482)
* fix: handle bom in text and json * add test for text and arraybuffer as well
1 parent a4ea5f9 commit 6425e20

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/body.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ export default class Body {
145145
* @return Promise
146146
*/
147147
async json() {
148-
const buffer = await consumeBody(this);
149-
return JSON.parse(buffer.toString());
148+
const text = await this.text();
149+
return JSON.parse(text);
150150
}
151151

152152
/**
@@ -156,7 +156,7 @@ export default class Body {
156156
*/
157157
async text() {
158158
const buffer = await consumeBody(this);
159-
return buffer.toString();
159+
return new TextDecoder().decode(buffer);
160160
}
161161

162162
/**

test/response.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,21 @@ describe('Response', () => {
7777
expect(res.headers.get('a')).to.equal('1');
7878
});
7979

80+
it('should decode responses containing BOM to json', async () => {
81+
const json = await new Response('\uFEFF{"a":1}').json();
82+
expect(json.a).to.equal(1);
83+
});
84+
85+
it('should decode responses containing BOM to text', async () => {
86+
const text = await new Response('\uFEFF{"a":1}').text();
87+
expect(text).to.equal('{"a":1}');
88+
});
89+
90+
it('should keep BOM when getting raw bytes', async () => {
91+
const ab = await new Response('\uFEFF{"a":1}').arrayBuffer();
92+
expect(ab.byteLength).to.equal(10);
93+
});
94+
8095
it('should support text() method', () => {
8196
const res = new Response('a=1');
8297
return res.text().then(result => {

0 commit comments

Comments
 (0)