ReadableStream.tee Branches A Stream

Branch one ReadableStream into two independent readers with tee, then drain both branches concurrently.

JavascriptData Fetching

Code

javascriptsnippet
26 lines
function sourceStream() {
  return new ReadableStream({
    start(controller) {
      controller.enqueue('first');
      controller.enqueue('second');
      controller.close();
    },
  });
}

async function collect(stream) {
  const chunks = [];
  for await (const chunk of stream) {
    chunks.push(chunk);
  }
  return chunks;
}

async function main() {
  const [left, right] = sourceStream().tee();
  const results = await Promise.all([collect(left), collect(right)]);
  console.log('left:', results[0].join('|'));
  console.log('right:', results[1].join('|'));
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

left: first|second
right: first|second

What the code does

ReadableStream.tee Branches A Stream keeps everything in the functions sourceStream, collect and main.

The cycling part of this snippet is for await (const chunk of stream). The asynchronous flow is linearized with await, keeping failure handling local.

The return value is newly constructed — inputs are never handed back.

Applying it

Signature: function sourceStream()

The demo output is labeled (left:, right:), so every printed line maps back to its originating operation.

The entry point wires sourceStream and collect together — run it once and the whole demo flows.

Statements that matter

const results = await Promise.all([collect(left), collect(right)]);
for await (const chunk of stream) {
  chunks.push(chunk);
}
return new ReadableStream({
  start(controller) {
    controller.enqueue('first');
    controller.enqueue('second');
    controller.close();
  },
});

FAQ

Does `sourceStream` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What does ReadableStream.tee Branches A Stream print when run?
The script runs standalone; its 2 labeled outputs include `left:`, `right:`.