Node.js: How to Compress a File using Gzip format

Updated: November 29, 2021 By: A Goodman Post a comment

In Node.js, you can compress a file using the Gzip format by using streams. We can get the job done with just a few lines of code and there is no need to install any third-party packages.


// Example
const { createReadStream, createWriteStream } = require("fs");
const { createGzip } = require("zlib");

// Create a gzip function for reusable purpose
const compressFile = (filePath) => {
  const stream = createReadStream(filePath);
    .on("finish", () =>
      console.log(`Successfully compressed the file at ${filePath}`)

// You can compress text files, images, SQL files, and many other file types.

Don’t forget to use your own file paths when running the preceding code snippet.

My screenshot:

You can improve the code above by adding error handling so that you can use it for production with confidence.

Further reading:

You can also check out our Node.js category page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles