What is inflateSync() in Node.js zlib Module?

The inflateSync function in Node.js zlib Module

The inflateSync function uses Inflate to decompress the provided data and returns the result in a buffer. The inflateSync function is a member function of the zlib class in the Node.js zlib Module.

The syntax of the inflateSync function is as follows:

zlib.inflateSync(buffer[,options])

Parameters

  • buffer is the data that is to be decompressed. It can be any of the following types:
    • Buffer
    • TypedArray
    • DataView
    • ArrayBuffer
    • string
  • options is an optional object that contains zlib options.

Return value

  • inflateSync() returns a Buffer instance containing the decompressed data.

Description

The inflateSync function decompresses the data provided as the buffer argument and returns the results in an instance of Buffer.

Note: The difference between inflateSync and inflate is that the latter takes a callback function because the decompression happens on a separate thread. The former takes no callback function because the decompression happens on the same thread that inflateSync is called on.

Example usage of the inflateSync function

The following code snippet provides an example of how to use the inflateSync function:

const zlib = require('zlib');
const rawData = 'Hello World!';
const compressedData = zlib.deflateSync(rawData);
const decompressedData = zlib.inflateSync(compressedData);
console.log("Decompressed Data (Buffer):", decompressedData);
console.log("Decompressed Data (String):", decompressedData.toString());

In the example above, the string Hello World!, stored in the rawData variable, is compressed using the deflateSync function. The compressed data in the compressedData variable is then decompressed using the inflateSync function. The decompressedData is printed on the standard output as a Buffer instance as well as a string.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved