MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Buffers and Streams: Readable, Writable & Pipeline for Large Files0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
2.1CommonJS vs ES Modules & Package.json Dependency Management2.2File System Operations: Sync, Async & Promises API (fs/promises)2.3EventEmitter Pattern & Custom Event Architecture2.4Buffers and Streams: Readable, Writable & Pipeline for Large Files
HomeTutorialsNode.js & Express.jsBuffers and Streams: Readable, Writable & Pipeline for Large Files
Native HTTP Server vs Express Framework Philosophy

Buffers and Streams: Readable, Writable & Pipeline for Large Files

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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):

1// Allocate buffer of 10 bytes initialized with zeros
2const buf = Buffer.alloc(10);
3 
4// Create buffer from UTF-8 string
5const strBuf = Buffer.from('Hello Node.js', 'utf-8');
6console.log(strBuf); // <Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>
7console.log(strBuf.toString('hex')); // Hexadecimal representation
8console.log(strBuf.toString('base64')); // Base64 encoding

2. The 4 Fundamental Stream Types

  1. 1
    Readable Streams: Source of data to read from (fs.createReadStream, http.IncomingMessage).
  2. 2
    Writable Streams: Destination to write data into (fs.createWriteStream, http.ServerResponse).
  3. 3
    Duplex Streams: Both Readable and Writable simultaneously (TCP socket).
  4. 4
    Transform 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:

1import fs from 'node:fs';
2import zlib from 'node:zlib';
3import { pipeline } from 'node:stream/promises';
4 
5async function compressLargeLogFile(inputPath, outputPath) {
6 try {
7 const readStream = fs.createReadStream(inputPath);
8 const gzipTransform = zlib.createGzip();
9 const writeStream = fs.createWriteStream(outputPath);
10 
11 // pipeline manages backpressure and ensures all streams close cleanly on failure
12 await pipeline(readStream, gzipTransform, writeStream);
13 console.log('File compressed successfully with zero memory overhead!');
14 } catch (err) {
15 console.error('Pipeline failed:', err.message);
16 }
17}
18 
19compressLargeLogFile('./access-5gb.log', './access-5gb.log.gz');

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.


Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Where is the memory for a Node.js Buffer allocated?
Question 2
Why is streaming preferred over fs.readFile() when handling multi-gigabyte files in a backend API?
Question 3
What is "backpressure" in Node.js streams?
Question 4
Which built-in utility handles error cleanup and automatically tears down streams when an error occurs during piped execution?
Question 5
Which type of stream is zlib.createGzip(), which takes uncompressed bytes and outputs compressed bytes?

Next Lesson

Native HTTP Server vs Express Framework Philosophy

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
EventEmitter Pattern & Custom Event ArchitectureNative HTTP Server vs Express Framework Philosophy

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext