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(" / "));
})();- Expected result: The console prints first / second.
- close indicates no further chunks will be enqueued.
- 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