Skip to content

Commit d434bb7

Browse files
authored
perf: optimize consumeEnd (#2510)
1 parent 5d63bb3 commit d434bb7

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

lib/api/readable.js

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@ const assert = require('assert')
66
const { Readable } = require('stream')
77
const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors')
88
const util = require('../core/util')
9-
const { ReadableStreamFrom, toUSVString } = require('../core/util')
10-
11-
let Blob
9+
const { ReadableStreamFrom } = require('../core/util')
1210

1311
const kConsume = Symbol('kConsume')
1412
const kReading = Symbol('kReading')
@@ -267,14 +265,35 @@ function consumeStart (consume) {
267265
}
268266
}
269267

268+
/**
269+
* @param {Buffer[]} chunks
270+
* @param {number} length
271+
*/
272+
function chunksDecode (chunks, length) {
273+
if (chunks.length === 0 || length === 0) {
274+
return ''
275+
}
276+
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length)
277+
278+
const start =
279+
buffer.length >= 3 &&
280+
// Skip BOM.
281+
buffer[0] === 0xef &&
282+
buffer[1] === 0xbb &&
283+
buffer[2] === 0xbf
284+
? 3
285+
: 0
286+
return buffer.utf8Slice(start, buffer.length - start)
287+
}
288+
270289
function consumeEnd (consume) {
271290
const { type, body, resolve, stream, length } = consume
272291

273292
try {
274293
if (type === 'text') {
275-
resolve(toUSVString(Buffer.concat(body)))
294+
resolve(chunksDecode(body, length))
276295
} else if (type === 'json') {
277-
resolve(JSON.parse(Buffer.concat(body)))
296+
resolve(JSON.parse(chunksDecode(body, length)))
278297
} else if (type === 'arrayBuffer') {
279298
const dst = new Uint8Array(length)
280299

@@ -286,9 +305,6 @@ function consumeEnd (consume) {
286305

287306
resolve(dst.buffer)
288307
} else if (type === 'blob') {
289-
if (!Blob) {
290-
Blob = require('buffer').Blob
291-
}
292308
resolve(new Blob(body, { type: stream[kContentType] }))
293309
}
294310

0 commit comments

Comments
 (0)