@@ -121,6 +121,11 @@ class BodyReadable extends Readable {
121
121
return consume ( this , 'blob' )
122
122
}
123
123
124
+ // https://fetch.spec.whatwg.org/#dom-body-bytes
125
+ async bytes ( ) {
126
+ return consume ( this , 'bytes' )
127
+ }
128
+
124
129
// https://fetch.spec.whatwg.org/#dom-body-arraybuffer
125
130
async arrayBuffer ( ) {
126
131
return consume ( this , 'arrayBuffer' )
@@ -306,6 +311,31 @@ function chunksDecode (chunks, length) {
306
311
return buffer . utf8Slice ( start , bufferLength )
307
312
}
308
313
314
+ /**
315
+ * @param {Buffer[] } chunks
316
+ * @param {number } length
317
+ * @returns {Uint8Array }
318
+ */
319
+ function chunksConcat ( chunks , length ) {
320
+ if ( chunks . length === 0 || length === 0 ) {
321
+ return new Uint8Array ( 0 )
322
+ }
323
+ if ( chunks . length === 1 ) {
324
+ // fast-path
325
+ return new Uint8Array ( chunks [ 0 ] )
326
+ }
327
+ const buffer = new Uint8Array ( Buffer . allocUnsafeSlow ( length ) . buffer )
328
+
329
+ let offset = 0
330
+ for ( let i = 0 ; i < chunks . length ; ++ i ) {
331
+ const chunk = chunks [ i ]
332
+ buffer . set ( chunk , offset )
333
+ offset += chunk . length
334
+ }
335
+
336
+ return buffer
337
+ }
338
+
309
339
function consumeEnd ( consume ) {
310
340
const { type, body, resolve, stream, length } = consume
311
341
@@ -315,17 +345,11 @@ function consumeEnd (consume) {
315
345
} else if ( type === 'json' ) {
316
346
resolve ( JSON . parse ( chunksDecode ( body , length ) ) )
317
347
} else if ( type === 'arrayBuffer' ) {
318
- const dst = new Uint8Array ( length )
319
-
320
- let pos = 0
321
- for ( const buf of body ) {
322
- dst . set ( buf , pos )
323
- pos += buf . byteLength
324
- }
325
-
326
- resolve ( dst . buffer )
348
+ resolve ( chunksConcat ( body , length ) . buffer )
327
349
} else if ( type === 'blob' ) {
328
350
resolve ( new Blob ( body , { type : stream [ kContentType ] } ) )
351
+ } else if ( type === 'bytes' ) {
352
+ resolve ( chunksConcat ( body , length ) )
329
353
}
330
354
331
355
consumeFinish ( consume )
0 commit comments