What is the gzip method of the zlib module in Node.js?

The gzip method of the zlib module in Node.js serves as an APIApplication Programming Interface for data compression.

The process is illustrated below:

To use the gzip method, you will need to import the zlib module into the program, as shown below:

const zlib = require('zlib');

The prototype of the gzip method is shown below:

gzip(buffer, [,options], callback)

Parameters

The gzip method takes the following parameters:

  • buffer: The data to be compressed. This parameter may be of type Buffer, TypedArray, DataView, ArrayBuffer, or string.

  • options: An optional parameter that represents an options object.

  • callback: The callback function.

Return value

The gzip method returns a compressed chunk of data.

Example

The code below shows how the gzip method works in Node.js:

const zlib = require('zlib');
// initilaizing uncompressed data
var uncompressed = "Learn zlib with Educative"
// compressing data
zlib.gzip(uncompressed, {chunkSize : 1000} , (error, data) => {
console.log("base64:")
if(!error)
{
// convert to base64
console.log(data.toString('base64'));
}
else{
// output error
console.log(err);
}
console.log("\nhex:")
if(!error)
{
// convert to hex
console.log(data.toString('hex'));
}
else{
// output error
console.log(err);
}
});
console.log("Data after compression:\n")

Explanation

First, a string that represents the uncompressed chunk of data is initialized.

Then, the gzip method in line 77 proceeds to compress the provided data. In this particular example, the options parameter specifies that data chunks should have a maximum size of 10001000 bytes. The callback parameter holds a function that compresses the provided data chunk into both base64 and hex encodings, in lines 1414 and 2626, respectively. The compressed chunks of data are then output.

Note: You can read up further on the zlib module and its methods here.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved