Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js require Module
Next article icon

Node.js Zlib Module

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The zlib module in Node.js is used for compressing and decompressing data. It uses Gzip and Deflate/Inflate algorithms to reduce data size, improving performance and saving bandwidth in Node.js applications.

Zlib Module in Node.js

The zlib module helps developers compress and decompress data streams or buffers using different compression methods. It's useful for handling large amounts of data that need to be sent over a network or stored efficiently. Built on the widely used zlib C library, it provides robust data compression.

Example: Compress a file (demofile.txt) into a gzip file (mygzipfile.txt.gz):

var fs = require('fs');
var zlib = require('zlib');

var x = fs.createReadStream('demofile.txt');
var y = fs.createWriteStream('mygzipfile.txt.gz');
var gzip = zlib.createGzip();
x.pipe(gzip).pipe(y);

Installation Step (Optional)

Installation is an optional step as it is inbuilt Node.js module. Install the Zlib module using the following command:

npm install zlib

Importing the Module

To use the zlib module in your Node.js application, simply import it as below:

const zlib = require('zlib');

Explore this Zlib Module Complete Reference to discover detailed explanations, advanced usage examples, and expert tips for mastering its powerful features to enhance your Node.js data processing.

Features

  • Easy Compression and Decompression : The zlib module allows you to compress and decompress files, buffers, or streams with various compression algorithms, such as Gzip and Deflate.
  • Stream Handling : Quickly compress or decompress files, buffers, or streams using popular algorithms like Gzip and Deflate.
  • Buffer Operations : Whether you're dealing with text or binary data, zlib makes it simple to compress and decompress data stored in buffers.
  • Custom Compression Levels : You can specify custom compression levels to balance between compression speed and efficiency, depending on your application’s needs.

Zlib Methods

The zlib module provides several methods for compression and decompression. Here's a summary of the key methods:

Method

Description

zlib.gzip()

Compresses data using Gzip

zlib.gunzip()

Decompresses Gzip-compressed data

zlib.deflate()

Compresses data using the Deflate algorithm

zlib.inflate()

Decompresses Deflate-compressed data

zlib.deflateRaw()

Compresses data using the Deflate algorithm without headers or checksums

zlib.inflateRaw()

Decompresses data compressed with deflateRaw()

zlib.brotliCompress()

Compresses data using the Brotli algorithm, a newer compression method offering better ratios

zlib.brotliDecompress()

Decompresses Brotli-compressed data.

Example 1: Compressing a String

This example compresses a chat message using Gzip to show how to reduce its size for storage or transmission.

JavaScript
const zlib = require('zlib');

const s_in = 'This is a sample string to compress.';

zlib.gzip(s_in, (err, compressedBuffer) => {
    if (err) {
        console.error('Compression error:', err);
    } else {
        console.log('Compressed Buffer:', compressedBuffer);
        console.log('Compressed Buffer (Hex):', compressedBuffer.toString('hex'));
    }
});

Output

Screenshot-2024-08-12-143811
compression

Example 2: Decompressing a Gzip Buffer

This example shows how to use the zlib.gunzip() method to decompress a Gzip-compressed buffer back to its original string.

JavaScript
console.clear();
const zlib = require("zlib");

const compressedBuffer = Buffer.from("your_hex_string_here", "hex");
zlib.gunzip(compressedBuffer, (err, buffer) => {
    if (err) {
        console.error("Error decompressing:", err);
    } else {
        console.log("Decompressed String:", buffer.toString());
    }
});

Output

Screenshot-2024-08-10-233639
Gzip Buffer

Benefits of Zlib Module

  • Efficient Data Compression: The zlib module allows you to reduce the size of your data, which is important for optimizing storage and bandwidth usage in large-scale applications.
  • Built-In Support: As a core Node.js module, zlib is always available without the need for external dependencies, making it convenient to use.
  • Flexible Compression Options: With support for multiple algorithms and custom compression levels, zlib offers flexibility to meet various performance and efficiency requirements.
  • Stream and Buffer Handling: The module’s ability to handle both streams and buffers makes it versatile for different data processing needs in Node.js applications.

Summary

The zlib module in Node.js is a versatile tool for compressing and decompressing data, offering support for various algorithms and custom compression levels. Whether you're looking to optimize network transmission or save space in your storage systems, zlib provides the necessary tools to handle data efficiently. As a core module, it is an essential part of the Node.js ecosystem, suitable for developers aiming to build high-performance applications.

Recent Articles on Node.js Zlib Module:

  • Why Zlib is used in Node.js ?
  • Node.js zlib.constants Property
  • Node.js zlib.createBrotliCompress() Method
  • Node.js zlib.createBrotliDecompress() Method
  • Node.js zlib.createUnzip() Method
  • Node.js zlib.createDeflateRaw() Method
  • Node.js zlib.createGunzip() Method
  • Node.js zlib.createInflateRaw() Method
  • Node.js zlib.createDeflate() Method
  • Node.js zlib.createInflate() Method
  • Node.js zlib.gzip() Method
  • Node.js zlib.bytesWritten Property
  • Node.js zlib.close() Method
  • Node.js zlib.flush() Method
  • Node.js zlib.brotliCompress() Method
  • Node.js zlib.brotliCompressSync() Method
  • Node.js zlib.brotliDecompress() Method
  • Node.js zlib.brotliDecompressSync() Method
  • Node.js zlib.deflate() Method
  • Node.js zlib.deflateSync() Method
  • Node.js zlib.deflateRaw() Method

Next Article
Node.js require Module

A

abhaykjyo2
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js
  • Node.js-Zlib-module

Similar Reads

    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js V8 Module
    The v8 module in Node.js is a core module that provides an interface to interact with the V8 JavaScript engine, which is the engine that Node.js uses to execute JavaScript code. This module exposes a variety of V8-specific APIs that allow developers to manage memory usage, optimize performance, and
    5 min read
    Node.js VM Module
    The VM (Virtual Machine) module in Node.js lets you safely run JavaScript code in a separate, isolated environment. This feature is especially handy when you need to execute code without affecting the rest of your application, making it ideal for handling untrusted code or creating distinct executio
    4 min read
    Node.js require Module
    The primary object exported by the require() module is a function. When NodeJS invokes this require() function, it does so with a singular argument - the file path. This invocation triggers a sequence of five pivotal steps: Resolving and Loading: The process begins with the resolution and loading of
    3 min read
    Node.js zlib.gzip() Method
    The zlib.gzip() method is an inbuilt application programming interface of the Zlib module which is used to compress a chunk of data.  Syntax: zlib.gzip( buffer, options, callback ) Parameters: This method accepts three parameters as mentioned above and described below: buffer: It can be of type Buff
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences