From d434bb7b6468eb5179e8af0f42ac56969b7be3cd Mon Sep 17 00:00:00 2001 From: tsctx <91457664+tsctx@users.noreply.github.com> Date: Sun, 10 Dec 2023 00:18:21 +0900 Subject: [PATCH] perf: optimize consumeEnd (#2510) --- lib/api/readable.js | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/lib/api/readable.js b/lib/api/readable.js index e6e71c4554c..8ea6d512f60 100644 --- a/lib/api/readable.js +++ b/lib/api/readable.js @@ -6,9 +6,7 @@ const assert = require('assert') const { Readable } = require('stream') const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors') const util = require('../core/util') -const { ReadableStreamFrom, toUSVString } = require('../core/util') - -let Blob +const { ReadableStreamFrom } = require('../core/util') const kConsume = Symbol('kConsume') const kReading = Symbol('kReading') @@ -267,14 +265,35 @@ function consumeStart (consume) { } } +/** + * @param {Buffer[]} chunks + * @param {number} length + */ +function chunksDecode (chunks, length) { + if (chunks.length === 0 || length === 0) { + return '' + } + const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) + + const start = + buffer.length >= 3 && + // Skip BOM. + buffer[0] === 0xef && + buffer[1] === 0xbb && + buffer[2] === 0xbf + ? 3 + : 0 + return buffer.utf8Slice(start, buffer.length - start) +} + function consumeEnd (consume) { const { type, body, resolve, stream, length } = consume try { if (type === 'text') { - resolve(toUSVString(Buffer.concat(body))) + resolve(chunksDecode(body, length)) } else if (type === 'json') { - resolve(JSON.parse(Buffer.concat(body))) + resolve(JSON.parse(chunksDecode(body, length))) } else if (type === 'arrayBuffer') { const dst = new Uint8Array(length) @@ -286,9 +305,6 @@ function consumeEnd (consume) { resolve(dst.buffer) } else if (type === 'blob') { - if (!Blob) { - Blob = require('buffer').Blob - } resolve(new Blob(body, { type: stream[kContentType] })) }