0
# Readable Streams
1
2
Comprehensive readable stream functionality for creating data sources that can be read from, with support for both default and byte streams, async iteration, and BYOB (Bring Your Own Buffer) reading.
3
4
## Capabilities
5
6
### ReadableStream Class
7
8
The main readable stream class that represents a source of data from which you can read.
9
10
```typescript { .api }
11
/**
12
* A readable stream represents a source of data, from which you can read.
13
*/
14
class ReadableStream<R = any> implements AsyncIterable<R> {
15
constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
16
constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });
17
18
/** Whether or not the readable stream is locked to a reader */
19
readonly locked: boolean;
20
21
/** Cancels the stream, signaling a loss of interest in the stream by a consumer */
22
cancel(reason?: any): Promise<void>;
23
24
/** Creates a ReadableStreamDefaultReader and locks the stream to the new reader */
25
getReader(): ReadableStreamDefaultReader<R>;
26
27
/** Creates a ReadableStreamBYOBReader and locks the stream to the new reader */
28
getReader(options: { mode: 'byob' }): ReadableStreamBYOBReader;
29
30
/** Provides a convenient, chainable way of piping this readable stream through a transform stream */
31
pipeThrough<RS extends ReadableStream>(
32
transform: ReadableWritablePair<R, RS>,
33
options?: StreamPipeOptions
34
): RS;
35
36
/** Pipes this readable stream to a given writable stream */
37
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
38
39
/** Tees this readable stream, returning a two-element array containing the two resulting branches */
40
tee(): [ReadableStream<R>, ReadableStream<R>];
41
42
/** Asynchronously iterates over the chunks in the stream's internal queue */
43
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
44
45
/** Asynchronously iterates over the chunks in the stream's internal queue */
46
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
47
48
/** Creates a new ReadableStream wrapping the provided iterable or async iterable */
49
static from<R>(asyncIterable: Iterable<R> | AsyncIterable<R> | ReadableStreamLike<R>): ReadableStream<R>;
50
}
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import { ReadableStream } from "web-streams-polyfill";
57
58
// Create a simple readable stream
59
const stream = new ReadableStream({
60
start(controller) {
61
controller.enqueue("chunk 1");
62
controller.enqueue("chunk 2");
63
controller.close();
64
}
65
});
66
67
// Read using async iteration
68
for await (const chunk of stream) {
69
console.log(chunk);
70
}
71
72
// Create from an async iterable
73
async function* generateData() {
74
yield "item 1";
75
yield "item 2";
76
yield "item 3";
77
}
78
79
const streamFromGenerator = ReadableStream.from(generateData());
80
```
81
82
### ReadableStreamDefaultReader
83
84
Default reader for readable streams that provides methods to read data and manage the stream's lock.
85
86
```typescript { .api }
87
/**
88
* Default reader for readable streams
89
*/
90
class ReadableStreamDefaultReader<R> {
91
constructor(stream: ReadableStream<R>);
92
93
/** Promise that will be fulfilled when the stream becomes closed or rejected if the stream ever errors */
94
readonly closed: Promise<undefined>;
95
96
/** Cancel the associated stream */
97
cancel(reason?: any): Promise<void>;
98
99
/** Read the next chunk from the stream's internal queue */
100
read(): Promise<ReadableStreamDefaultReadResult<R>>;
101
102
/** Release the reader's lock on the corresponding stream */
103
releaseLock(): void;
104
}
105
```
106
107
**Usage Examples:**
108
109
```typescript
110
import { ReadableStream } from "web-streams-polyfill";
111
112
const stream = new ReadableStream({
113
start(controller) {
114
controller.enqueue("Hello");
115
controller.enqueue("World");
116
controller.close();
117
}
118
});
119
120
const reader = stream.getReader();
121
122
try {
123
while (true) {
124
const { done, value } = await reader.read();
125
if (done) break;
126
console.log(value);
127
}
128
} finally {
129
reader.releaseLock();
130
}
131
```
132
133
### ReadableStreamBYOBReader
134
135
Bring-Your-Own-Buffer reader for byte streams that allows reading directly into user-provided buffers.
136
137
```typescript { .api }
138
/**
139
* BYOB (Bring Your Own Buffer) reader for byte streams
140
*/
141
class ReadableStreamBYOBReader {
142
constructor(stream: ReadableStream<Uint8Array>);
143
144
/** Promise that will be fulfilled when the stream becomes closed or rejected if the stream ever errors */
145
readonly closed: Promise<undefined>;
146
147
/** Cancel the associated stream */
148
cancel(reason?: any): Promise<void>;
149
150
/** Read data into the provided buffer view */
151
read<T extends ArrayBufferView>(
152
view: T,
153
options?: { min?: number }
154
): Promise<ReadableStreamBYOBReadResult<T>>;
155
156
/** Release the reader's lock on the corresponding stream */
157
releaseLock(): void;
158
}
159
```
160
161
**Usage Examples:**
162
163
```typescript
164
import { ReadableStream } from "web-streams-polyfill";
165
166
// Create a byte stream
167
const byteStream = new ReadableStream({
168
type: 'bytes',
169
start(controller) {
170
const chunk = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
171
controller.enqueue(chunk);
172
controller.close();
173
}
174
});
175
176
const reader = byteStream.getReader({ mode: 'byob' });
177
const buffer = new Uint8Array(1024);
178
179
try {
180
const { done, value } = await reader.read(buffer);
181
if (!done) {
182
console.log(new TextDecoder().decode(value));
183
}
184
} finally {
185
reader.releaseLock();
186
}
187
```
188
189
### ReadableStreamDefaultController
190
191
Controller provided to underlying sources for managing the readable stream's internal state and queue.
192
193
```typescript { .api }
194
/**
195
* Controller for default readable streams
196
*/
197
class ReadableStreamDefaultController<R> {
198
/** Returns the desired size to fill the controlled stream's internal queue */
199
readonly desiredSize: number | null;
200
201
/** Close the controlled readable stream */
202
close(): void;
203
204
/** Enqueue a chunk into the controlled readable stream */
205
enqueue(chunk: R): void;
206
207
/** Error the controlled readable stream */
208
error(error: any): void;
209
}
210
```
211
212
### ReadableByteStreamController
213
214
Controller provided to byte stream underlying sources for managing byte streams with BYOB support.
215
216
```typescript { .api }
217
/**
218
* Controller for byte readable streams
219
*/
220
class ReadableByteStreamController {
221
/** Returns the current BYOB pull request, or null if there isn't one */
222
readonly byobRequest: ReadableStreamBYOBRequest | null;
223
224
/** Returns the desired size to fill the controlled stream's internal queue */
225
readonly desiredSize: number | null;
226
227
/** Close the controlled readable stream */
228
close(): void;
229
230
/** Enqueue a chunk into the controlled readable stream */
231
enqueue(chunk: ArrayBufferView): void;
232
233
/** Error the controlled readable stream */
234
error(error: any): void;
235
}
236
```
237
238
### ReadableStreamBYOBRequest
239
240
Represents a BYOB pull request, allowing underlying byte sources to respond with data.
241
242
```typescript { .api }
243
/**
244
* Represents a BYOB (Bring Your Own Buffer) read request
245
*/
246
class ReadableStreamBYOBRequest {
247
/** The ArrayBufferView to be filled, or null if the request was already responded to */
248
readonly view: ArrayBufferView<ArrayBuffer> | null;
249
250
/** Indicates to the associated stream that bytesWritten bytes were written into the view */
251
respond(bytesWritten: number): void;
252
253
/** Indicates to the associated stream that the request is being responded to with a new view */
254
respondWithNewView(view: ArrayBufferView): void;
255
}
256
```
257
258
## Underlying Source Types
259
260
### UnderlyingSource Interface
261
262
Configuration object for default readable streams.
263
264
```typescript { .api }
265
interface UnderlyingSource<R = any> {
266
/** Called immediately during construction of the ReadableStream */
267
start?: (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
268
269
/** Called when the stream's internal queue of chunks becomes not full */
270
pull?: (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
271
272
/** Called when the stream is canceled */
273
cancel?: (reason: any) => void | PromiseLike<void>;
274
275
/** Must be undefined for default streams */
276
type?: undefined;
277
}
278
```
279
280
### UnderlyingByteSource Interface
281
282
Configuration object for byte readable streams with BYOB support.
283
284
```typescript { .api }
285
interface UnderlyingByteSource {
286
/** Called immediately during construction of the ReadableStream */
287
start?: (controller: ReadableByteStreamController) => void | PromiseLike<void>;
288
289
/** Called when the stream's internal queue of chunks becomes not full */
290
pull?: (controller: ReadableByteStreamController) => void | PromiseLike<void>;
291
292
/** Called when the stream is canceled */
293
cancel?: (reason: any) => void | PromiseLike<void>;
294
295
/** Must be 'bytes' for byte streams */
296
type: 'bytes';
297
298
/** Size of chunks to automatically allocate when using default readers */
299
autoAllocateChunkSize?: number;
300
}
301
```
302
303
## Result and Options Types
304
305
```typescript { .api }
306
type ReadableStreamDefaultReadResult<T> =
307
| { done: false; value: T }
308
| { done: true; value: undefined };
309
310
type ReadableStreamBYOBReadResult<T extends ArrayBufferView> =
311
| { done: false; value: T }
312
| { done: true; value: T | undefined };
313
314
interface ReadableStreamIteratorOptions {
315
/** Prevent canceling the stream when the iterator's return() method is called */
316
preventCancel?: boolean;
317
}
318
319
interface ReadableStreamAsyncIterator<R> extends AsyncIterableIterator<R> {
320
next(): Promise<IteratorResult<R, undefined>>;
321
return(value?: any): Promise<IteratorResult<any>>;
322
}
323
324
interface ReadableStreamLike<R = any> {
325
readonly locked: boolean;
326
getReader(): ReadableStreamDefaultReaderLike<R>;
327
}
328
329
interface ReadableStreamDefaultReaderLike<R = any> {
330
readonly closed: Promise<undefined>;
331
cancel(reason?: any): Promise<void>;
332
read(): Promise<ReadableStreamDefaultReadResult<R>>;
333
releaseLock(): void;
334
}
335
336
type ReadableStreamReader<R> = ReadableStreamDefaultReader<R> | ReadableStreamBYOBReader;
337
338
interface ReadableStreamGetReaderOptions {
339
/** The type of reader to create ('byob' for BYOB reader, undefined for default reader) */
340
mode?: 'byob';
341
}
342
343
interface ReadableStreamBYOBReaderReadOptions {
344
/** Minimum number of bytes to read */
345
min?: number;
346
}
347
```
348
349
## Callback Types
350
351
```typescript { .api }
352
type UnderlyingSourceStartCallback<R> = (
353
controller: ReadableStreamDefaultController<R>
354
) => void | PromiseLike<void>;
355
356
type UnderlyingSourcePullCallback<R> = (
357
controller: ReadableStreamDefaultController<R>
358
) => void | PromiseLike<void>;
359
360
type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike<void>;
361
362
type UnderlyingByteSourceStartCallback = (
363
controller: ReadableByteStreamController
364
) => void | PromiseLike<void>;
365
366
type UnderlyingByteSourcePullCallback = (
367
controller: ReadableByteStreamController
368
) => void | PromiseLike<void>;
369
```