Compress and Decompress Files in Node.js with Zlib

This article provides a practical guide on how to compress and decompress files using the built-in zlib module in Node.js. You will learn how to use streams to efficiently handle large files, reducing their size using Gzip compression and restoring them to their original state using Gunzip decompression.

File Compression (Gzip)

To compress a file in Node.js, you use the zlib.createGzip() method alongside the fs (File System) module. Using streams ensures that the file is processed in small chunks, which prevents high memory consumption.

Here is the code to compress a file named input.txt into a compressed file named input.txt.gz:

const fs = require('fs');
const zlib = require('zlib');

// Create a gzip object
const gzip = zlib.createGzip();

// Create read and write streams
const source = fs.createReadStream('input.txt');
const destination = fs.createWriteStream('input.txt.gz');

// Pipe the read stream into the gzip transform stream, then to the write stream
source.pipe(gzip).pipe(destination);

destination.on('finish', () => {
  console.log('File successfully compressed using Gzip.');
});

File Decompression (Gunzip)

To restore the compressed .gz file back to its original format, you use the zlib.createGunzip() method. This processes the compressed stream and outputs the original uncompressed data.

Here is the code to decompress input.txt.gz back into a plain text file named output.txt:

const fs = require('fs');
const zlib = require('zlib');

// Create a gunzip object
const gunzip = zlib.createGunzip();

// Create read and write streams
const source = fs.createReadStream('input.txt.gz');
const destination = fs.createWriteStream('output.txt');

// Pipe the compressed read stream into the gunzip transform stream, then to the destination file
source.pipe(gunzip).pipe(destination);

destination.on('finish', () => {
  console.log('File successfully decompressed.');
});

Error Handling

When working with streams and file systems, it is important to handle potential errors (such as missing files or permission issues) to prevent your Node.js application from crashing. You can listen for the error event on any of the streams:

source.on('error', (err) => console.error('Read error:', err.message));
gzip.on('error', (err) => console.error('Compression error:', err.message));
destination.on('error', (err) => console.error('Write error:', err.message));