Performance: Streaming with ReadableStream and WritableStream
Streaming affects how quickly data starts to appear on the page and how smoothly it flows, improving load speed and responsiveness.
const response = await fetch(url); const reader = response.body.getReader(); while(true) { const { done, value } = await reader.read(); if(done) break; processChunk(value); }
const response = await fetch(url); const data = await response.text(); processData(data);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Full data fetch before processing | Single large DOM update | 1 large reflow | High paint cost due to big update | [X] Bad |
| Streaming with ReadableStream | Multiple small DOM updates | Multiple small reflows | Lower paint cost per update | [OK] Good |
ReadableStream in Deno?ReadableStream is designed to produce data chunks that can be read by consumers.WritableStream accepts data chunks to be written, which is the opposite role.WritableStream in Deno?new WritableStream() and an object with a write method.new WritableStream({ write(chunk) { ... } }). Others misuse syntax or omit new.const readable = new ReadableStream({
start(controller) {
controller.enqueue('Hello');
controller.enqueue('World');
controller.close();
}
});
const reader = readable.getReader();
(async () => {
let result = '';
while(true) {
const { done, value } = await reader.read();
if (done) break;
result += value + ' ';
}
console.log(result.trim());
})();result, and stops when done is true.result is 'Hello World ' which trims to 'Hello World'.const writable = new WritableStream({
write(chunk) {
console.log(chunk.toUpperCase());
}
});
const writer = writable.getWriter();
await writer.write(123);
await writer.close();chunk.toUpperCase(), which only works on strings.toUpperCase() method, causing a runtime error.ReadableStream of text chunks to uppercase and write them to a WritableStream. Which approach correctly implements this in Deno?TransformStream that changes chunks to uppercase.Pass the test and this pattern moves unknown