Streams — reading a big file in pieces, and backpressure¶
Level: 301 · for readers who have copied a file too big to read at once
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: write() returning false is backpressure: the writable's buffer has reached its highWaterMark, 64 KiB by default (16 KiB on Windows). Nothing stops you writing anyway — memory just grows — unless you wait for drain or let pipeline wait for you.
Keywords: stream.pipeline, highWaterMark, drain, createReadStream, Writable
What the finished page will answer¶
- After how many 1 KiB writes to a slow
Writabledoeswrite()returnfalse, and what does it return if you keep writing? - What is
writableLengthafter ignoringfalseand writing 1 MiB more, and when doesdrainfire? - What chunk sizes does
createReadStreamdeliver for a 200 KiB file, and how does itshighWaterMarkoption change them? - How does peak
rsscompare when copying a large file with an uncheckedwriteloop and withpipeline? - What does
pipelinedo with an error in the middle stage, and what happens to the other two streams?
Examples it will need¶
-
streams_write_returns_false_js.js— the write at which a slow Writable first returns false, itswritableLengthafter writing on regardless, and whendrainfires -
streams_read_chunk_sizes_js.js— the chunk sizescreateReadStreamyields for a 200 KiB file at the default and at a 16 KiBhighWaterMark -
streams_pipeline_memory_js.js— peakrsscopying a large generated file with an unchecked write loop and withpipeline
See also¶
- Files —
readFile, which loads the whole file at once - stdin, stdout and pipes — stdout is a writable stream too
EventEmitter—data,drainanderrorare emitter events- Async iteration —
for awaitover a readable stream - Concurrency: Backpressure ↗ — backpressure as a concept, across languages
- Concurrency: What stops a fast producer from filling memory? ↗ — a bounded queue pushing back on a fast producer
- Rust: Backpressure ↗ — backpressure in a Tokio server