How to zip or unzip files using NodeJS and Express JS framework

How to zip or unzip files using NodeJS

Compressing or uncompressing files is an important feature in a web application. Suppose you are working on a web application that needs to zip or unzip files using NodeJS. So this tutorial is going to explain how to zip or unzip files using NodeJS. In a previous tutorial we explored how to Zip, save and download files using codeigniter.

In this tutorial following tasks are going to be performed.

1. Create an application to zip or unzip files using NodeJS.

2. Install express-easy-zip module to compress files or directories

3. Install unzip NodeJS module to unzip a file

zip or unzip files using nodejs

You can view the app below.

zip or unzip files using NodeJs

Create an application to zip or unzip file using NodeJS

If you have not installed NodeJS yet, then please visit NodeJS website, download and install NodeJS. To generate an Express and NodeJS application, you need to install. express generator tool

Express generator installs express tool to generate a skeleton for NodeJs Express application.

Installing express generator

Open command prompt.

$ npm install express-generator -g

Generate a NodeJS Express application

After express generator installation. Type following command on command line to generate a NodeJS, express application.

express --view=pug nodejs-zip-unzip-files

zip or unzip files using nodejs

Here pug is used as template engine in view files. This command will generate an application named nodejs-zip-unzip-files. Next type cd nodejs-zip-unzip-files && npm install command to install dependencies in node_modules folder in project.

cd nodejs-zip-unzip-files && npm install

Add folder and files to be zipped

We need a folder and some files inside folder to zip. So open public folder and add a new folder named Uploads, This folder contains files to be compressed. Add some images or text files in this folder.

zip or unzip files using nodejs

Install express-easy-zip module

Open command line, go to project folder, and install express-easy-zip node module. This module is used to zip or compress files.

npm install express-easy-zip

Creating Zip and Unzip routes

Open project in your favorite IDE such as Sublime text, Eclipse or brackets.

zip or unzip files using nodejs

Create a View page

Open index.pug file inside Views folder. Add code below to this file under block content.

h1= title

  h4 1. Click on Zip and Download Button to Zip and download all files from Uploads folder

  h4 2. Click on Unzip Button to unzip files from compressed folder and save to Unzip folder

  br

  p

    a.button-link(href = '/zip') Zip and Download Files

    a.button-link(href = '/unzip') Unzip Files

Also you need to update the style.css inside stylesheets folder under public directory.

Edit title in Index Route

Open index.js file in Routes folder. Inside ‘/’ route. Change title of page var title = ‘Zip or Unzip files using NodeJS’;.

Add Zip and Unzip routes

Open index.js file in Routes folder. Add following code to the top

var zip = require('express-easy-zip');

Then add

router.use(zip());

Now add a new route /zip. Add following code inside the file.

router.get('/zip', function(req, res, next) {

  var dirPath = __dirname + "/../public/uploads";

  res.zip({

       files: [

           {   
                content: 'This is a test string',      
               
                name: 'test-file',
               
                mode: 0755,

                comment: 'comment-for-the-file - test file',

                date: new Date(),

                type: 'file' },
           

           { path: dirPath, name: 'uploads' }    
       ],
       
         filename: 'nodejs-zip-files.zip'
   
    });

});

First uploads directory inside public folder is assigned to dirPath variable. Then res object’s zip method is assigned a files array. Inside files array an object is passed. In object we passed a file contents dynamically with its name, mode, created date and type. This file named test-file is going to be compressed.

Next a folder uploads with full path is given. Contents of this folder are going to be compressed. Lastly name of zip file is given.

Running the application to zip or unzip file using nodejs

To run this application, go to project folder on Command Prompt. Type

node bin/www

Now open browser and type following URL is address bar.

http://localhost:3000

You can view our application running on port 3000. When user clicks on Zip and Download Files link button. /zip route is executed.

A zip file with a text file named test-file and uploads folder is created with name ‘Nodejs-zip-file.zip‘. User is prompted to save the generated zip file. Detail about option to be used in the zip can be read here

zip or unzip files using NodeJs

zip or unzip files using NodeJs

Unzip a file using NodeJS

To unzip a compressed file contents, first you need to install unzip NodeJS module.

Install unzip module

Unzip module uncompresses a zip file contents. Open command line, and type following command.

npm install unzip

Next open index.js file in routes folder, Add line below.

var unzip = require('unzip');

Add following code inside it.

//unzip / uncompress a file

router.get('/unzip', function(req, res, next) {

  var dirPath  = __dirname + "/../public/compressed/nodejs-zip-files.zip";

  var destPath = __dirname + "/../public/unzip";

  fs.createReadStream(dirPath).pipe(unzip.Extract({ path: destPath }));

  res.redirect('/');

});

What are Nodejs Streams?

Consider streams as objects. These objects can read data from a source and write data to a destination continuously. A stream can be readable to perform read operation, writable to perform write operation, duplex to perform both operations or a transform.

A new route unzip is added in index.js file. Inside route, path to an already compressed zip file is added. Zip file is inside compressed folder under public directory.

zip or unzip files using nodejs

var dirPath = __dirname + "/../public/compressed/nodejs-zip-files.zip";

Next path to unzip folder is added, where compressed file contents will be uncompressed.

var destPath = __dirname + "/../public/unzip";

Lastly using fs module, a read stream is created using createReadStream. Inside readStream zip file path is given. readStream reads the contents of this file and passes to pipe stream.

Pipe stream takes input from one stream and pipes it to unzip module’s Extract method. Inside extract method destination path is given. File is unzipped in destination folder successfully and user is redirected to ‘/’ route.

Summary

In this tutorial you have learned how to zip or unzip files using NodeJS. Zip and unzip modules were installed and compressed files inside uploads folder. Then uncompressed a zip file present inside compressed directory. You can download source code  from this link.  Leave your feedback or comments below.

Please follow us on twitter to stay informed about upcoming tutorials.