Lesson 14 / 28
Streams
Process data piece by piece instead of loading it all into memory.
Readable & writable
A readable stream emits chunks of data (data events); a writable stream accepts chunks via .write(). Files, HTTP requests/responses, and process stdin/stdout are all streams.
Piping a file
pipe connects a readable stream straight to a writable one — Node handles backpressure for you.
import { createReadStream, createWriteStream } from "node:fs";
createReadStream("big-input.txt")
.pipe(createWriteStream("copy.txt"));Quick check: Why prefer streams over readFile for a very large file?
- Streams process data in chunks instead of loading it all into memory
- Streams are always faster to write code for
- readFile cannot read files over 1KB
Answer
Streams process data in chunks instead of loading it all into memory — Streams keep memory usage low and let you start processing before the whole file has arrived.