Buffers and Streams: Readable, Writable & Pipeline for Large Files
Buffers and Streams: Readable, Writable & Pipeline for Large Files
When dealing with large files, video feeds, or high-throughput network packets, loading the entire payload into RAM via fs.readFile() will instantly exhaust server memory and crash the process. Node.js solves this with Buffers (raw binary memory) and Streams (processing data chunk-by-chunk in real time).
1. Understanding Buffers
A Buffer is a fixed-size chunk of memory allocated outside the V8 JavaScript heap. It stores raw binary bytes (octets):
2. The 4 Fundamental Stream Types
- 1Readable Streams: Source of data to read from (
fs.createReadStream,http.IncomingMessage). - 2Writable Streams: Destination to write data into (
fs.createWriteStream,http.ServerResponse). - 3Duplex Streams: Both Readable and Writable simultaneously (TCP socket).
- 4Transform Streams: Modifies or transforms the data chunk as it passes through (
zlib.createGzip, crypto cipher).
3. Streaming Huge Files with Backpressure and pipeline
Using .pipe() is convenient, but if a stream errors mid-transmission, old .pipe() calls often leak open file descriptors. Modern Node.js standardizes on stream.promises.pipeline to handle errors and cleanup automatically:
4. What is Backpressure?
If a Readable stream produces data faster than the Writable destination can write to disk or network (e.g. reading from an NVMe SSD at 3 GB/s and sending over a 10 Mbps internet connection), incoming chunks accumulate in RAM. Backpressure pauses the readable stream until the writable stream drains its buffer, maintaining a constant, predictable memory footprint under 30 MB regardless of file size.
Multiple Choice Questions
Buffer allocated?fs.readFile() when handling multi-gigabyte files in a backend API?zlib.createGzip(), which takes uncompressed bytes and outputs compressed bytes?Native HTTP Server vs Express Framework Philosophy
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| EventEmitter Pattern & Custom Event Architecture | Native HTTP Server vs Express Framework Philosophy |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.