Skip to main content

How To Compress File In Node.js

ยท 2 min read
Parth Maheta

In Node.js, you can use the built-in zlib module to compress and decompress files using various compression algorithms. Here's a simple example demonstrating how to compress a file using gzip compression:

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

const inputFilePath = 'example.txt';
const outputFilePath = 'example.txt.gz';

const compressFile = (inputPath, outputPath) => {
const readStream = fs.createReadStream(inputPath);
const writeStream = fs.createWriteStream(outputPath);
const gzip = zlib.createGzip();

// Pipe the read stream through gzip and then to the write stream

writeStream.on('finish', () => {
console.log('File compressed successfully.');

compressFile(inputFilePath, outputFilePath);

In this example:

  1. The fs.createReadStream method creates a readable stream from the input file (example.txt).
  2. The zlib.createGzip method creates a gzip transform stream.
  3. The fs.createWriteStream method creates a writable stream for the output file (example.txt.gz).
  4. The pipe method is used to pipe the data from the read stream through the gzip transform stream and then to the write stream.

After running this script, you'll have a compressed file (example.txt.gz) in the same directory as your script.

Remember to handle errors appropriately, for example, by listening to the 'error' events on the streams:

readStream.on('error', (err) => {
console.error(`Error reading stream: ${err.message}`);

gzip.on('error', (err) => {
console.error(`Error compressing stream: ${err.message}`);

writeStream.on('error', (err) => {
console.error(`Error writing compressed stream: ${err.message}`);

This script uses gzip compression, but you can also use other compression algorithms provided by the zlib module, such as zlib.createDeflate or zlib.createBrotliCompress, depending on your requirements and the availability of algorithms on your system.