Open In App

Node.js zlib.gzip() Method

Last Updated : 28 Apr, 2025
Suggest changes
Share
Like Article
Like
Report

The zlib.gzip() method is an inbuilt application programming interface of the Zlib module which is used to compress a chunk of data. 

Syntax:

zlib.gzip( buffer, options, callback )

Parameters: This method accepts three parameters as mentioned above and described below:

  • buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string.
  • options: It is an optional parameter that holds the zlib options.
  • callback: It holds the callback function.

Return Value: It returns the chunk of data after compression. 

The below examples illustrate the use of zlib.gzip() method in Node.js: 

Example 1: 

javascript
// Node.js program to demonstrate the  // gzip() method // Including zlib module const zlib = require("zlib"); // Declaring input and assigning // it a value string const input = "Geek"; // Calling gzip method zlib.gzip(input, (err, buffer) => {  if (!err) {  console.log(buffer.toString('base64'));  }  else {  console.log(err);  } }); console.log("Data Compressed..."); 

Output:

Data Compressed... H4sIAAAAAAAAA3NPTc0GAGGRcasEAAAA

Example 2: 

javascript
// Node.js program to demonstrate the  // gzip() method // Including zlib module const zlib = require("zlib"); // Declaring input and assigning // it a value string const input = "Geek"; // Calling gzip method zlib.gzip(input, (err, buffer) => {  if (!err) {  console.log(buffer.toString('hex'));  }  else {  console.log(err);  } }); console.log("Data Compressed..."); 

Output:

Hint: hit control+c anytime to enter REPL. Data Compressed... 1f8b0800000000000003734f4dcd0600619171ab04000000

Reference: https://nodejs.org/api/zlib.html#zlib_zlib_gzip_buffer_options_callback


Explore