How to use 'zlib.unzip()' function in Node.js
In this shot, we learn how to decompress a string or a buffer using the zlib module in Node.js.
The zlib.unzip() function is a built-in module in Node.js that accepts, at most, three distinct parameters.
Syntax
The zlib.unzip() function looks like this when implemented in a program:
zlib.unzip(buffer, options, callback)
-
buffer: We use buffers to represent a fixed-length sequence of bytes. In theunzip()module, we can include buffers of<TypedArray>,<DataView>,<ArrayBuffer>, and<string>type. -
options: These are optional objects that we can include inunzip()as a parameter. -
callback: This is a function that is executed upon the method returning.
Code
Let’s look at the following implementation of the zlib.unzip() module in Node.js.
var zlib = require("zlib");var text1 = "Hello this is a string";zlib.gzip(text1, (err, buffer) => {zlib.unzip(buffer, (err, buffer) => {console.log("Decompressed string in base64 format:");console.log(buffer.toString('base64'));});});var text2 = "Hello this is another string";zlib.gzip(text2, (err, buffer) => {zlib.unzip(buffer, (err, buffer) => {console.log("\nDecompressed string in utf8 format:");console.log(buffer.toString('utf8'));});});
Explanation
The above code example imports the necessary library zlib required to execute the following code appropriately.
The zlib.unzip() takes three parameters, as mentioned previously. This function takes a text, an err (error parameter), and a buffer.
text1 is decompressed into
base64 to print an unreadable message, as shown on the console. text2 is displayed in utf-8 format.
Note: The
==sequence in the output generated fortext1indicates padding of one byte when a 24-bit section is not complete. If it contained=, it would mean a padding of two bytes.
Free Resources