What is the createDeflate method of the zlib module in Node.js?
The createDeflate method of the zlib module in Node.js serves as an
The process is illustrated below:
To use the createDeflate method, you will need to import the zlib module into the program, as shown below:
const zlib = require('zlib');
The prototype of the createDeflate method is shown below:
createDeflate([options])
Parameters
The createDeflate method takes a single optional parameter, i.e., an options object.
Return value
The createDeflate method returns a newly created Deflate object.
Example
The code below shows how the createDeflate method works in Node.js:
// including the required modulesvar zlib = require('zlib');var fs = require('fs');// creating a Deflate objectvar compressor = zlib.createDeflate({level : 9, chunkSize: 1000});// setup readable stream for input filevar read = fs.createReadStream('test.txt');// setup writeable stream to zip filevar write = fs.createWriteStream('test.txt.gz');// transform stream to compress datavar compressed_stream = read.pipe(compressor)// pipe compressed data to zip filecompressed_stream.pipe(write);console.log("The file has been zipped!");
Explanation
First, a Deflate object, compressor, is initialized through the createDeflate method in line . compressor will be used to zip an input file. The level option is set to as part of the options parameter to ensure maximum compression. The value of level can be changed or omitted based on your requirements. The chunkSize option is set to , which specifies the maximum size of data chunks.
Next, the code opens a readable stream from the input file test.txt. A writable stream to the zipped file test.txt.gz is also created.
The data from the readable stream is piped to the Deflate object, compressor, in line . compressor proceeds to compress the input file. The newly compressed data is piped to the writable stream, and the zipped file test.txt.gz is created.
Note: You can read up further on the
zlibmodule and its methods here.
Free Resources