Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: optimize consumeEnd #2510

Merged
merged 12 commits into from
Dec 9, 2023
32 changes: 24 additions & 8 deletions lib/api/readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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)
ronag marked this conversation as resolved.
Show resolved Hide resolved
ronag marked this conversation as resolved.
Show resolved Hide resolved
}

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)

Expand All @@ -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] }))
}

Expand Down