Codectionary / Developer documentation / JavaScript

Consuming a ReadableStream

ReadableStream delivers chunks over time. A reader locks the stream while it is in use; read() returns an object with value and done. Streams help process incremental data without collecting the entire payload, but producers and consumers still need a cancellation and error policy.

Syntax

const reader = stream.getReader();
const { value, done } = await reader.read();

Examples

Consuming a ReadableStream: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: The console prints first / second.

(async () => {
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue("first");
      controller.enqueue("second");
      controller.close();
    }
  });
  const reader = stream.getReader();
  const chunks = [];
  try {
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      chunks.push(value);
    }
  } finally { reader.releaseLock(); }
  console.log(chunks.join(" / "));
})();
  1. Expected result: The console prints first / second.
  2. close indicates no further chunks will be enqueued.
  3. releaseLock makes the stream available to another reader; it does not itself cancel the producer.

Best practices

  • Cancel the reader if abandoning remaining work.
  • For large real streams, process chunks incrementally instead of retaining every chunk as this small demonstration does.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading