The deflate method of the zlib module in Node.js serves as an
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)
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.
The deflate method returns a compressed chunk of data.
The code below shows how the deflate method works in Node.js:
const zlib = require('zlib');// initilaizing uncompressed datavar uncompressed = "Learn zlib with Educative"// compressing datazlib.deflate(uncompressed, {chunkSize : 1000}, (error, data) => {if(!error){// convert to hexconsole.log(data.toString('hex'));}else{// output errorconsole.log(err);}});console.log("Data after compression:\n")
First, a string that represents the uncompressed chunk of data is initialized.
The deflate method in line proceeds to compress the provided data. In this particular example, the options parameter indicates that data chunks should have a maximum size of bytes. The callback parameter holds a function that compresses the provided data chunk into a hex encoding in line . The compressed data is then output.
Note: You can read up further on the
zlibmodule and its methods here.
Free Resources