Node Js File Compression with Zlib Gzip and Streams Tutorial

Node gzip example; If you are a node developer, then how do you manage the file compression?

If you state that you don’t know a thing about compression in node, then worry not.

We have brought a handy step by step guide to upscale your knowledge about file compression feature in node js.

In this quick tutorial, we will help you learn how to compress a file without using the third-party module.

To make the file compression in node, we will use the Gzip format and streams.

To use the createGzip method in node, we can use the zlib library, which is a default programming module of the node. It allows creating the new Gzip object for easy File Compression in the node.

How to Use Zlib Gzip Method to Compress a File in Node Js

  • Step 1: Create App Directory
  • Step 2: Generate Package Json File
  • Step 3: Set Up App File
  • Step 4: Create File Compress
  • Step 5: Run Application

Create App Directory

We need a blank folder, you can create a new folder using the following command.

mkdir node-gzip

You now need to enter into the folder.

cd node-gzip

Generate Package Json File

We need a package.json file, in this file we have to keep the project information.

Following command can initiate the process of creating the package file.

npm init

The package.json file typically can be found at your project root.

Set Up App File

We need a file where we can write the code, create a server.js file at the root of your app.

In the next step, we will bind the server.js file with node command.

For that, make sure to visit package.json file and add the code to make the script available for node command.

  "scripts": {
    "start": "node server.js"
  },

Create File Compress

Now, you have to open the server.js file afterwards insert the following code within the app file.

let { createGzip } = require('zlib')
let { createWriteStream, createReadStream } = require('fs')

let gzipFiles = (fileLoc) => {
  let fileStream = createReadStream(fileLoc)
  fileStream
    .pipe(createGzip())
    .pipe(createWriteStream(`${fileLoc}.gz`))
    .on('finish', () => console.log(`File has been compressed: ${fileLoc}`))
}

gzipFiles('./demo-img.jpg')

gzipFiles('./demo.txt')

Run Application

Eventually, you are ready to test the app and let us keep demo-img.jpg and demo.txt in the gzipFiles() method.

However, you may use any file of your choice. You may use the following command from terminal.

node server.js

You can now check your node folder, you will see the compressed file in your project directory.

Node Js File Compression with Zlib Gzip and Streams Tutorial

Summary

File compression is a data compression process used to reduce the logical size of a file.

In this Zlib gzip example, we learned how to create a basic node app moreover built functionality to compress image and text files.