Skip to content

Commit

Permalink
fetch: make readAllBytes "sync"
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak committed Jan 14, 2025
1 parent e3928ed commit 9a7e1ba
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
2 changes: 1 addition & 1 deletion lib/web/fetch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ async function mainFetch (fetchParams, recursive = false) {
}

// 4. Fully read response’s body given processBody and processBodyError.
await fullyReadBody(response.body, processBody, processBodyError)
fullyReadBody(response.body, processBody, processBodyError)
} else {
// 21. Otherwise, run fetch finale given fetchParams and response.
fetchFinale(fetchParams, response)
Expand Down
38 changes: 21 additions & 17 deletions lib/web/fetch/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -1240,42 +1240,46 @@ function isomorphicEncode (input) {

/**
* @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
* @see https://streams.spec.whatwg.org/#read-loop
* @param {ReadableStreamDefaultReader} reader
* @param {(bytes: Uint8Array) => void} successSteps
* @param {(error: Error) => void} failureSteps
*/
async function readAllBytes (reader, successSteps, failureSteps) {
function readAllBytes (reader, successSteps, failureSteps) {
const bytes = []
let byteLength = 0

try {
do {
const { done, value: chunk } = await reader.read()
readLoop(reader, bytes, successSteps, failureSteps)
}

/**
* @see https://streams.spec.whatwg.org/#read-loop
* @param {ReadableStreamDefaultReader} reader
* @param {Uint8Array[]} bytes
* @param {(bytes: Uint8Array) => void} successSteps
* @param {(error: Error) => void} failureSteps
*/
function readLoop (reader, bytes, successSteps, failureSteps) {
reader
.read()
.then(({ done, value: chunk }) => {
if (done) {
// 1. Call successSteps with bytes.
successSteps(Buffer.concat(bytes, byteLength))
// 1. Call successSteps with bytes.
successSteps(Buffer.concat(bytes))
return
}

// 1. If chunk is not a Uint8Array object, call failureSteps
// with a TypeError and abort these steps.
if (!isUint8Array(chunk)) {
failureSteps(TypeError('Received non-Uint8Array chunk'))
failureSteps(new TypeError('Received non-Uint8Array chunk'))
return
}

// 2. Append the bytes represented by chunk to bytes.
bytes.push(chunk)
byteLength += chunk.length

// 3. Read-loop given reader, bytes, successSteps, and failureSteps.
} while (true)
} catch (e) {
// 1. Call failureSteps with e.
failureSteps(e)
}
// 3. Read-loop given reader, bytes, successSteps, and failureSteps.
readLoop(reader, bytes, successSteps, failureSteps)
})
.catch(failureSteps)
}

/**
Expand Down

0 comments on commit 9a7e1ba

Please sign in to comment.