Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js zlib.gzip() Method

Improve Article
Save Article
  • Last Updated : 12 Oct, 2021
Improve Article
Save Article

The zlib.gzip() method is an inbuilt application programming interface of the Zlib module which is used to compresses 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.

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

Example 1:




// Node.js program to demonstrate the     
// gzip() method
  
// Including zlib module
const zlib = require("zlib");
  
// Declaring input and assigning
// it a value string
var 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:




// Node.js program to demonstrate the     
// gzip() method
  
// Including zlib module
const zlib = require("zlib");
  
// Declaring input and assigning
// it a value string
var 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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!