search
HomeWeb Front-endCSS TutorialWeb Streams Everywhere (and Fetch for Node.js)

Web Streams Everywhere (and Fetch for Node.js)

Jake Archibald's 2016 prediction of "the year of web streams" might have been slightly ahead of its time. However, the Streams Standard, initially proposed in 2014, is now a reality, consistently implemented across modern browsers (with Firefox catching up) and Node.js (and Deno).

Understanding Streams

Streaming efficiently handles large data resources by breaking them into smaller "chunks" and processing them sequentially. This avoids waiting for a complete download before processing begins, enabling progressive data handling.

Three main stream types exist: readable, writable, and transform streams. Readable streams provide data chunks (from sources like files or HTTP connections). Transform streams (optional) modify these chunks. Finally, writable streams receive the processed data.

Web Streams: Cross-Platform Consistency

Node.js initially had its own stream implementation, often considered complex. The WHATWG web standard for streams offers a significant improvement, now referred to as "web streams" in Node.js documentation. While the original Node.js streams remain, the web standard API coexists, promoting cross-platform code and simplifying development.

Deno, also created by Node.js's original author, fully supports web streams, mirroring browser APIs. Cloudflare Workers and Deno Deploy also leverage this standardized approach.

fetch() and Readable Streams

The most common way to create a readable stream is using fetch(). The response.body of a fetch() call is a readable stream.

fetch('data.txt')
.then(response => console.log(response.body));

The console log reveals several useful stream methods. As the specification states, a readable stream can be directly piped to a writable stream using pipeTo(), or piped through transform streams using pipeThrough().

Node.js core lacks built-in fetch support. node-fetch (a popular library) returns a Node stream, not a WHATWG stream. Undici, a newer HTTP/1.1 client from the Node.js team, offers a modern alternative to http.request, providing a fetch implementation where response.body does return a web stream. Undici is likely to become the recommended HTTP request handler in Node.js. Once installed (npm install undici), it functions similarly to browser fetch. The following example pipes a stream through a transform stream:

import { fetch } from 'undici';
import { TextDecoderStream } from 'node:stream/web';

async function fetchStream() {
  const response = await fetch('https://example.com');
  const stream = response.body;
  const textStream = stream.pipeThrough(new TextDecoderStream());
  // ... further processing of textStream ...
}

response.body is synchronous; await isn't needed. Browser code is almost identical, omitting the import statements as fetch and TextDecoderStream are globally available. Deno also has native support.

Asynchronous Iteration

The for-await-of loop provides asynchronous iteration, extending the for-of loop's functionality to asynchronous iterables (like streams and arrays of promises).

async function fetchAndLogStream() {
  const response = await fetch('https://example.com');
  const stream = response.body;
  const textStream = stream.pipeThrough(new TextDecoderStream());

  for await (const chunk of textStream) {
    console.log(chunk);
  }
}

fetchAndLogStream();

This works in Node.js, Deno, and modern browsers (though browser stream support is still developing).

Additional Readable Stream Sources

While fetch() is prevalent, other methods create readable streams: Blob.stream() and File.stream() (requiring import { Blob } from 'buffer'; in Node.js). In browsers, an <input type="file"> element easily provides a file stream:

const fileStream = document.querySelector('input').files[0].stream();

Node.js 17 introduces FileHandle.readableWebStream() from fs/promises.open():

import { open } from 'node:fs/promises';

// ... (open file and process stream) ...

Stream and Promise Integration

For post-stream completion actions, promises are useful:

someReadableStream
.pipeTo(someWritableStream)
.then(() => console.log("Data written"))
.catch(error => console.error("Error", error));

Or using await:

await someReadableStream.pipeTo(someWritableStream);

Custom Transform Stream Creation

Beyond TextDecoderStream (and TextEncoderStream), you can create custom transform streams using TransformStream. The constructor accepts an object with optional start, transform, and flush methods. transform performs the data transformation.

Here's a simplified (for illustrative purposes; use TextDecoderStream in production) text decoder:

const decoder = new TextDecoder();
const decodeStream = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(decoder.decode(chunk, {stream: true}));
  }
});

Similarly, you can create custom readable streams using ReadableStream, providing start, pull, and cancel functions. The start function uses controller.enqueue to add chunks.

Node Stream Interoperability

Node.js provides .fromWeb() and .toWeb() methods (in Node.js 17 ) for converting between Node streams and web streams.

Conclusion

The convergence of browser and Node.js APIs continues, with streams being a key part of this unification. While full front-end stream adoption is still underway (e.g., MediaStream isn't a readable stream yet), the future points towards broader stream utilization. The potential for efficient I/O and cross-platform development makes learning web streams worthwhile.

The above is the detailed content of Web Streams Everywhere (and Fetch for Node.js). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.