Skip to content

Commit

Permalink
perf: optimize consumeEnd (#2510)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx authored Dec 9, 2023
1 parent 5d63bb3 commit d434bb7
Showing 1 changed file with 24 additions and 8 deletions.
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)
}

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

0 comments on commit d434bb7

Please sign in to comment.