Open In App

Node.js zlib.flush() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The flush() method is called on a compression stream so that it can compel zlib to return as much output as achievable at present. This output may be returned at the cost of corrupt compression quality but it can be useful when data is required to be accessible as early as possible.

Syntax:

zlib.flush()

Parameters: This method does not accept any parameters.

Return Value: It returns the data as much as possible at present.

Below examples illustrate the use of zlib.flush() method in Node.js:

Example 1:




// Node.js program to demonstrate the     
// zlib.flush() method
   
// Including zlib module
const zlib = require('zlib');
   
// Constructing createGzip and createGunzip
const input = zlib.createGzip();
const output = zlib.createGunzip();
   
// Piping
input.pipe(output);
   
// Write to stream
input.write('GeeksforGeeks');
   
// Calling flush method
input.flush();
   
// Check output
output.on('data', (d) => {
    console.log('Input: Data flush received ' 
    + d.length + ' bytes');
});
console.log("Program Complete!");


Output:

Program Complete!
Input: Data flush received 13 bytes

Example 2:




// Node.js program to demonstrate the     
// zlib.flush() method
  
// Including zlib module
const zlib = require('zlib');
  
// Constructing createGzip and createGunzip
const input = zlib.createGzip();
const output = zlib.createGunzip();
  
// Piping
input.pipe(output);
  
// Writing to a stream of data 19000 bytes
input.write('G'.repeat(19000));
  
// Calling flush method with callback
input.flush(() => {});
  
// Check output
output.on('data', (d) => {
    console.log('Input: Data flush with callback received ' 
    + d.length + ' bytes');
});
console.log("Program Complete!");


Output: So, after the byte size exceeds 16384 bytes then you need to callback flush method else data won’t be flushed fully.

Program Complete!
Input: Data flush with callback received 16384 bytes
Input: Data flush with callback received 2616 bytes

Reference: https://nodejs.org/api/zlib.html#zlib_flushing



Last Updated : 28 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads