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
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 typeBuffer,TypedArray,DataView,ArrayBuffer, orstring. -
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 datavar uncompressed = "Learn zlib with Educative"// compressing datazlib.gzip(uncompressed, {chunkSize : 1000} , (error, data) => {console.log("base64:")if(!error){// convert to base64console.log(data.toString('base64'));}else{// output errorconsole.log(err);}console.log("\nhex:")if(!error){// convert to hexconsole.log(data.toString('hex'));}else{// output errorconsole.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 proceeds to compress the provided data. In this particular example, the options parameter specifies that data chunks should have a maximum size of bytes.
The callback parameter holds a function that compresses the provided data chunk into both base64 and hex encodings, in lines and , respectively. The compressed chunks of data are then output.
Note: You can read up further on the
zlibmodule and its methods here.
Free Resources