File archiving is an everyday activity in the modern world as everyone can attest to the advantages offered by compressing files or folders into smaller, portable formats.

The ZIP format is one of the most popular archive formats used in the world of computing, and it is a highly recommended choice for anyone that needs to convert raw files to archives for better storage, efficient transfer, or any other reason.

So, why should you consider compressing your files, and how can you compress files to ZIP and extract them back to their original state programmatically using Node.js?

Why Compress Files?

A lot of times, files and folders become very large, and sharing or transferring them becomes a problem because they’re either too big to store on a storage drive of a specific capacity, or they’re taking too long to upload to cloud storage.

In scenarios like this and many more, you should compress such files or folders into a much smaller size. Apart from easier file transfer, other reasons why you might consider compressing your files include:

What Are the Node.js Archiver and Unzipper Packages?

TheArchiverpackage’s official documentation describes the package as “a streaming interface for archive generation”. This implies that the Archiver package provides a library of functions that leverage Node.js streams to create compressed file archives.

The Archiver package supports multiple archive formats by default, including ZIP, GZIP, and TAR. The package also allows you to create archives from files and directories, and split large archives into smaller parts (multi-volume archives). It also allows you to exclude or filter files during compression.

TheUnzipperpackage is a very efficient package for extracting ZIP archives in Node.js. The package provides an easy-to-use API that allows developers to extract ZIP files with just a few lines of code.

The Archiver and Unzipper packages are the choices for this tutorial because they seamlessly integrate with the Node.jsfsmodule, ensuring smooth compatibility and simplicity.

How to Compress Files to ZIP Format in Node.js

Compressing filesto ZIP format in Node.js is easy just like in any other language, thanks to the Archiver package. To create ZIP archives in Node.js while following along in this section, you need a Node.js development environment set up on your computer.

You will create a simple Node.js script to compress a file and folder to ZIP format. Create a new Node project on your computer by running the following commands:

Next, you need to install the Archiver package in your project. Runnpm install archiver –savein your terminal to install it. When the package installation is complete, create a new file in the project directory and name it according to your preference, e.g.app.jsorarchiver.js.

Thefsmodule handles file operations, while the Archiver package will handle the compression of files and folders into ZIP archives, hence, the script requires both modules.

Creating ZIP Archives From Files

The following code is the implementation of a function that accepts a file as an argument and creates a compressed ZIP version of the file.

The function takes the filename of the file to compress and generates an output file with a similar name (with the only distinction being the addition of the ZIP file extension).

Then, the function generates a new archive with the compression level set to 9 (highest) and utilizes thepipefunction to transfer the output streams of the archive into the input of the output file.

Thefilefunction adds a file to the archive. It accepts the file path as a parameter and an optionaloptionsparameter where you’re able to specify the properties of the file in the archive.

Thenameoption designates the name of the file within the archive. If the option is not specified when adding a file to the archive, Archiver places the file within the archive based on its original path, preserving the directory structure.

However, when it is explicitly provided, Archiver adds the file to the archive without its original path, allowing for custom naming and organization within the archive.

Creating ZIP Archives From Folders

The process of creating ZIP archives from folders isn’t very different from the one for files. The main difference is the use of the Archiver package’sdirectoryfunction as opposed tofilein the previous function.

Below is the implementation of a function to compress a folder into a ZIP archive.

Thedirectoryfunction takes the folder path as its first argument and a flag as its second argument. The flag determines the placement of the folder within the archive.

When the flag is set tofalse, the resulting archive will only contain the contents of the folder, excluding the folder itself. But if the flag is set totrue, Archiver will include the folder itself in the generated archive

If you want to avoid contaminating the location where you’re extracting your archive with files from the compressed archive, you should think about setting theflagoption totrue. However, you may set it tofalse, if it better suits your purposes.

How to Decompress Files in Node.js

The process of extracting ZIP files in Node.js has multiple approaches and several libraries are available for use, but in this article, the Unzipper package is used.

Run the following command in your terminal to install the Unzipper package in your project.

After installing the package, import it into your code and implement the ZIP extraction function shown in the code below:

TheextractZipfunction is an asynchronous function that creates a read stream to read the content of the ZIP file, and extracts the file to the output path specified (it creates theextractedfolder if it doesn’t exist).

In the case of decompressing or extraction, there is no need to define different functions for files and folders, as a ZIP archive is a file irrespective of the content in it.

Below is a function you can add to the application, to test the functions you’ve created so far:

All the previous functions areJavaScript arrow functions, but the above function is different because it is anImmediately Invoked Function Expressionthatencapsulates the codewithin it and executes it immediately.

File Compression Is Beneficial in Building Efficient Applications

It should always be a goal to make your applications as efficient as they can be in order to serve users better and maintain an enjoyable user experience.

In scenarios where you need to transfer a lot of files within your application, consider compressing and decompressing the files while transmitting. Most modern programming languages provide support to compress and decompress files efficiently.