|
| 1 | +import { ReadableStream } from "stream/web"; |
1 | 2 | import { TextEncoder } from "util"; |
2 | 3 | import { Response } from "@miniflare/core"; |
3 | 4 | import { Headers } from "undici"; |
@@ -107,19 +108,27 @@ export function _getRangeResponse( |
107 | 108 | Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) |
108 | 109 | .toString() |
109 | 110 | .padStart(16, "0"); |
110 | | - const arrays: Uint8Array[] = []; |
111 | | - for (const [start, end] of ranges) { |
112 | | - const header = `--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${start}-${end}/${responseBody.byteLength}\r\n\r\n`; |
113 | | - arrays.push(encoder.encode(header)); |
114 | | - arrays.push(responseBody.slice(start, end + 1)); |
115 | | - arrays.push(encoder.encode("\r\n")); |
116 | | - } |
117 | | - arrays.push(encoder.encode(`--${boundary}--`)); |
| 111 | + const stream = new ReadableStream({ |
| 112 | + type: "bytes", |
| 113 | + pull(controller) { |
| 114 | + const range = ranges.shift(); |
| 115 | + if (range === undefined) { |
| 116 | + controller.enqueue(encoder.encode(`--${boundary}--`)); |
| 117 | + return controller.close(); |
| 118 | + } |
| 119 | + |
| 120 | + const [start, end] = range; |
| 121 | + const header = `--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${start}-${end}/${responseBody.byteLength}\r\n\r\n`; |
| 122 | + controller.enqueue(encoder.encode(header)); |
| 123 | + controller.enqueue(responseBody.slice(start, end + 1)); |
| 124 | + controller.enqueue(encoder.encode("\r\n")); |
| 125 | + }, |
| 126 | + }); |
118 | 127 | responseHeaders.set( |
119 | 128 | "Content-Type", |
120 | 129 | `multipart/byteranges; boundary=${boundary}` |
121 | 130 | ); |
122 | | - return new Response(Buffer.concat(arrays), { |
| 131 | + return new Response(stream, { |
123 | 132 | status: 206, // Partial Content |
124 | 133 | headers: responseHeaders, |
125 | 134 | }); |
|
0 commit comments