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 APIApplication Programming Interface that returns a new Deflate object.

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:

index.js
test.txt
// including the required modules
var zlib = require('zlib');
var fs = require('fs');
// creating a Deflate object
var compressor = zlib.createDeflate({level : 9, chunkSize: 1000});
// setup readable stream for input file
var read = fs.createReadStream('test.txt');
// setup writeable stream to zip file
var write = fs.createWriteStream('test.txt.gz');
// transform stream to compress data
var compressed_stream = read.pipe(compressor)
// pipe compressed data to zip file
compressed_stream.pipe(write);
console.log("The file has been zipped!");

Explanation

First, a Deflate object, compressor, is initialized through the createDeflate method in line 66. compressor will be used to zip an input file. The level option is set to 99 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 10001000, 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 1616. 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 zlib module and its methods here.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved