Repository navigation
asWebStream
asWebStream() creates a Web Streams {readable, writable} duplex pair from any function. It supports regular functions, asynchronous functions, generator functions, and asynchronous generator functions. The result is a native Web Streams pair — not a TransformStream — so it can be pipeTo'd / pipeThrough'd alongside any other Web Streams.
In most cases you don't need to use it directly. It is used internally by the chain() factory in stream-chain/web.
The example of usage:
import asWebStream from 'stream-chain/asWebStream.js';
// const {asWebStream} = require('stream-chain/asWebStream.js');The function accepts the following arguments:
-
fn— any function, generator function, asynchronous function, or asynchronous generator function. Iffnis already a Web Streams object (ReadableStream,WritableStream, or{readable, writable}pair) it is returned as-is. -
options— an optional object with the following fields. Defaults: Web Streams' built-in{highWaterMark: 1}count strategy on both sides.-
strategy— aQueuingStrategyapplied to both sides if no side-specific strategy is given. Shorthand for "use this for both." -
readableStrategy— aQueuingStrategyfor the readable side. Overridesstrategy. -
writableStrategy— aQueuingStrategyfor the writable side. Overridesstrategy.
-
The function returns {readable: ReadableStream, writable: WritableStream} — a Web Streams duplex pair. Writing chunks to writable runs them through fn; the results emerge from readable in order.
fn can use any special values defined in defs (and re-exported in chain()):
-
none,null,undefined— no value is produced.asWebStream()treatsnull/undefinedasnonefor consistency withasStream(). -
stop,Stop— terminates the stream: the stages after the one that stopped are flushed, then the readable side closes cleanly (see defs). -
many()— multiple (or none) values are produced. -
finalValue()— its payload is emitted; downstream functions in a chain are skipped.
Note: From a generator, don't yield none or many(...) (pointless); stop and finalValue(...) are supported — after issuing one, return. See defs for the full rule.
TransformStream's transform(chunk, controller) callback is expected to run to completion per chunk. If one chunk produces N output values (via many / a generator), and we want backpressure to wake between every push (to keep the queue bounded), the transform() callback would need to suspend mid-call — which the API doesn't allow. A manual {readable, writable} pair with a custom pull() callback hooking into a pending-drain Promise gives us per-item backpressure cleanly.
When controller.desiredSize drops to 0 after an enqueue, the next push returns a Promise that resolves only when the readable's pull() fires (i.e., the consumer requested more). The queue stays at hwm + 1 regardless of how many output values one input chunk produces. The wrapper runs on the same sync-when-possible executor as asStream, so synchronous stages stay synchronous — there is no blanket async penalty; the pipeline suspends only at a push that actually backpressures (or a genuinely async stage). A Web pair does suspend more often than a Node Duplex on the same work, but only because its default {highWaterMark: 1} count strategy makes every output enqueue a potential backpressure point (the Node Duplex defaults to hwm: 16); raise the strategy's highWaterMark to trade memory for fewer suspensions. Benefit: bounded memory under unbounded expansion. See highWaterMark for the cross-substrate background.
import asWebStream from 'stream-chain/asWebStream.js';
const {readable, writable} = asWebStream(x => x * x);
// pipeline-style usage
sourceReadable.pipeTo(writable);
const out = await readable.getReader().read();
// if source produces 1, 2, 3 -> out yields 1, 4, 9Tune backpressure:
const ws = asWebStream(fn, {
strategy: new CountQueuingStrategy({highWaterMark: 16})
});
// or per-side:
const ws2 = asWebStream(fn, {
readableStrategy: new CountQueuingStrategy({highWaterMark: 16}),
writableStrategy: new CountQueuingStrategy({highWaterMark: 4})
});asWebStream()'s duplex pair matches TransformStream's lifecycle semantics:
-
reader.cancel(reason)— cancels iteration on the readable side and propagates the reason to the writable side, which becomes errored. Producer's pendingwriter.write()rejects with the cancel reason. -
writer.abort(reason)— errors both sides with the reason. Any in-flight write awaiting backpressure wakes immediately (viacontroller.signal). -
User-function error — if
fnthrows (or returns a rejected Promise), both sides are errored with the thrown value. DownstreampipeTo'd stages observe the error.
-
asStream()— the Node Streams counterpart. -
chain() and the
stream-chain/websubpath — chain-of-chains over Web Streams. -
makeWebStreamPuller()— for consuming aReadableStreamas an async iterator. - highWaterMark — backpressure tuning.
- defs — special values and the generator-yields-plain convention.
Start here
API
Transducers
Adapters
I/O & helpers
Tuning & internals
Reference
stream-chain 2.x (legacy)