Node.js Zlib Module

Here is a complete, easy-to-understand guide to the Node.js Zlib Module, with examples for compression and decompression.


🌟 Node.js Zlib Module

The zlib module in Node.js provides compression and decompression functionalities using popular algorithms like:

  • Gzip

  • Deflate

  • Brotli (modern high-performance compression)

It is commonly used to:

✔ Compress files
✔ Decompress files
✔ Create zip-like buffers
✔ Stream compression (HTTP responses, file downloads)


Import Zlib



 


🗜️ 1. Gzip Compression

Compress a string


 

result is a Buffer.


🔄 2. Gzip Decompression


 


📄 3. Compress a File using Streams


 


📂 4. Decompress a File using Streams


 


🌀 5. Deflate Compression

Compress:


 

Decompress:



 


⚡ 6. Brotli Compression (Modern & Better)

Brotli is better than gzip for text-based resources like HTML, CSS, JS.

Compress:


 

Decompress:



 


🔁 7. Stream-based Brotli Example


 


🔧 8. Custom Compression Options


 


🧠 9. Compression Levels

Levels range from 0 → 9

  • 0 = no compression (fastest)

  • 9 = maximum compression (slowest)


📌 10. Use Cases of Zlib

✔ Compressing files before upload/download
✔ Creating .gz compressed logs
✔ Sending compressed data over sockets
✔ Compressing HTTP responses (Content-Encoding: gzip)
✔ Faster web performance (Brotli for web servers)

You may also like...