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

The deflate 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 deflate method, you will need to import the zlib module into the program, as shown below:

const zlib = require('zlib');

The prototype of the deflate method is shown below:

deflate(buffer, [,options], callback)

Parameters

The deflate 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 deflate method returns a compressed chunk of data.

Example

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

const zlib = require('zlib');
// initilaizing uncompressed data
var uncompressed = "Learn zlib with Educative"
// compressing data
zlib.deflate(uncompressed, {chunkSize : 1000}, (error, data) => {
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.

The deflate method in line 77 proceeds to compress the provided data. In this particular example, the options parameter indicates that data chunks should have a maximum size of 10001000 bytes. The callback parameter holds a function that compresses the provided data chunk into a hex encoding in line 1212. The compressed data is 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