Node.js `zlib`: Efficient Compression and Decompression of Data

Learn how to use Node.js's `zlib` module for efficient data compression and decompression using gzip and deflate/inflate algorithms. This tutorial covers both synchronous and asynchronous methods, including stream-based approaches for handling large files, improving network efficiency and reducing storage requirements.



Node.js ZLIB

The Node.js `zlib` module provides compression and decompression functionalities using algorithms like gzip and deflate/inflate. This is useful for reducing file sizes and improving network efficiency.

Using the ZLIB Module

Access the `zlib` module using `require('zlib')`:

Importing zlib

const zlib = require('zlib');
            

Compression and decompression are often done using streams for efficient handling of large files.

Example: Compressing a File

This example compresses a file named "input.txt" into "input.txt.gz":

Compressing a File

const zlib = require('zlib');
const gzip = zlib.createGzip();
const fs = require('fs');
const inp = fs.createReadStream('input.txt');
const out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
            

Make sure you have an "input.txt" file. Run this with `node zlib_example1.js`. A compressed "input.txt.gz" file will be created.

Example: Decompressing a File

This example decompresses "input.txt.gz" into "input2.txt":

Decompressing a File

const zlib = require('zlib');
const unzip = zlib.createGunzip(); // Use createGunzip for .gz files
const fs = require('fs');
const inp = fs.createReadStream('input.txt.gz');
const out = fs.createWriteStream('input2.txt');
inp.pipe(unzip).pipe(out);
            

Run with `node zlib_example2.js`. The decompressed content will be in "input2.txt". For best results, use a larger "input.txt" file (e.g., 40KB) to see the significant size reduction after compression (to around 1KB).

next →

← prev