Open In App

Node.js zlib.gzip() Method

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:

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: 




// 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: 




// 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


Article Tags :