@@ -4,6 +4,7 @@ const { redirectStatus } = require('./constants')
44const { performance } = require ( 'perf_hooks' )
55const { isBlobLike, toUSVString, ReadableStreamFrom } = require ( '../core/util' )
66const assert = require ( 'assert' )
7+ const { isUint8Array } = require ( 'util/types' )
78
89let File
910
@@ -438,6 +439,53 @@ function makeIterator (iterator, name) {
438439 return Object . setPrototypeOf ( { } , i )
439440}
440441
442+ /**
443+ * @see https://fetch.spec.whatwg.org/#body-fully-read
444+ */
445+ async function fullyReadBody ( body , processBody , processBodyError ) {
446+ // 1. If taskDestination is null, then set taskDestination to
447+ // the result of starting a new parallel queue.
448+
449+ // 2. Let promise be the result of fully reading body as promise
450+ // given body.
451+ try {
452+ /** @type {Uint8Array[] } */
453+ const chunks = [ ]
454+ let length = 0
455+
456+ const reader = body . stream . getReader ( )
457+
458+ while ( true ) {
459+ const { done, value } = await reader . read ( )
460+
461+ if ( done === true ) {
462+ break
463+ }
464+
465+ // read-loop chunk steps
466+ assert ( isUint8Array ( value ) )
467+
468+ chunks . push ( value )
469+ length += value . byteLength
470+ }
471+
472+ // 3. Let fulfilledSteps given a byte sequence bytes be to queue
473+ // a fetch task to run processBody given bytes, with
474+ // taskDestination.
475+ const fulfilledSteps = ( bytes ) => queueMicrotask ( ( ) => {
476+ processBody ( bytes )
477+ } )
478+
479+ fulfilledSteps ( Buffer . concat ( chunks , length ) )
480+ } catch ( err ) {
481+ // 4. Let rejectedSteps be to queue a fetch task to run
482+ // processBodyError, with taskDestination.
483+ queueMicrotask ( ( ) => processBodyError ( err ) )
484+ }
485+
486+ // 5. React to promise with fulfilledSteps and rejectedSteps.
487+ }
488+
441489/**
442490 * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
443491 */
@@ -477,5 +525,6 @@ module.exports = {
477525 isValidHeaderName,
478526 isValidHeaderValue,
479527 hasOwn,
480- isErrorLike
528+ isErrorLike,
529+ fullyReadBody
481530}
0 commit comments