concatenate-stream.js (666B)
1 'use strict'; 2 3 // Read all the chunks from a stream that returns BufferSource objects and 4 // concatenate them into a single Uint8Array. 5 async function concatenateStream(readableStream) { 6 const reader = readableStream.getReader(); 7 let totalSize = 0; 8 const buffers = []; 9 while (true) { 10 const { value, done } = await reader.read(); 11 if (done) { 12 break; 13 } 14 buffers.push(value); 15 totalSize += value.byteLength; 16 } 17 reader.releaseLock(); 18 const concatenated = new Uint8Array(totalSize); 19 let offset = 0; 20 for (const buffer of buffers) { 21 concatenated.set(buffer, offset); 22 offset += buffer.byteLength; 23 } 24 return concatenated; 25 }