ReadableStream and reader lifecycle
Quick answer
A ReadableStream delivers chunks over time. A reader acquires exclusive access and obtains successive results as promises.
How it works
new ReadableStream({start(controller),pull(controller),cancel(reason)}) defines a source; these hooks are optional. enqueue supplies chunks and close signals no more chunks. getReader() locks the stream. Await read() for {value,done} and release the lock when finished, including on errors. Release does not cancel the source. A generic stream may carry objects rather than bytes.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const s=new ReadableStream({start(c){c.enqueue(0);c.close();}});const r=s.getReader();const a=await r.read();console.log(s.locked,a.value,a.done);r.releaseLock();console.log(s.locked);})()Expected console output:
true 0 falsefalseZero is a valid chunk; releasing unlocks the stream.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const s=new ReadableStream({start(c){c.enqueue("a");c.close();}});const r=s.getReader();console.log((await r.read()).value,(await r.read()).done);r.releaseLock();})()Expected console output:
a trueClosing allows queued data to be read before completion.
Common mistakes
Do not try to acquire a second reader while locked. Check done rather than treating a falsy value as end.
Practice
Read a stream containing 0 and 2, preserving zero, then release the reader.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ReadableStream and reader lifecycle — Knowledge Check
Apply the concept and reason about local example output.
What does getReader do to an unlocked readable stream?
Does releaseLock alone cancel the readable source?
Which field should determine whether reading has finished?
What is the expected console output of ReadableStream and reader lifecycle example 1?
(async () => {const s=new ReadableStream({start(c){c.enqueue(0);c.close();}});const r=s.getReader();const a=await r.read();console.log(s.locked,a.value,a.done);r.releaseLock();console.log(s.locked);})()What is the expected console output of ReadableStream and reader lifecycle example 2?
(async () => {const s=new ReadableStream({start(c){c.enqueue("a");c.close();}});const r=s.getReader();console.log((await r.read()).value,(await r.read()).done);r.releaseLock();})()