How to Zip Files using Node & Express?

Published by Pawan Sargar on

How to zip files in Nodejs?

Nodejs is powerful, Nodejs with Expressjs is a superpower, and today we’ll see how easy it is to compress files in Node/Express.

You’ll find multiple methods to compress or zip files in Node, but in this post, I’ll try to show the easiest way to do it.

Before we get started, you need to have a basic understanding of Node and Express framework, like creating a basic server, using NPM packages, etc.

So, let’s get started.

This is what we’ll create –

File Structure –

  • public
    • uploads(files to compress)
  • app.js
  • index.html

Setup Server –

Let’s set up our Express application, create a new folder and open the terminal inside it.

npm init -y

#then

npm install express

#then

touch app.js index.html

This will initialize the NPM and install Express and all the required dependencies.

Now, open the folder in any code editor and enter the below code inside app.js.

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

app.listen(process.env.PORT || 5000, () => {
  console.log("server running on PORT 5000...");
});

Above snippet is the basic boilerplate code to set up a basic Express application, you can run it by entering node app.js inside the terminal.

Install required Packages –

To accomplish this task we’ll need to use certain NPM packages which help us to compress files in our application.

  • Multer – This package will help us to upload any files onto the server. This package makes it really easy to upload any files to the backend, or to the database.
  • ADM Zip – This NPM package will allow us to easily zip or compress any files. The files uploaded by Multer will be compressed by this library.
npm install multer adm-zip

Do check out the documentation of Multer and ADM ZIP package for better understanding.

Initialize Packages and Compress files –

const express = require("express");

const multer = require("multer");
const admzip = require("adm-zip");

//Node built in modules
const fs = require("fs");
const path = require("path");

const app = express();

//setting public as a static folder
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));

//Multer Setup
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
//setting up the upload folder
    cb(null, "public/uploads");
  },
  filename: (req, file, cb) => {
    cb(
      null,
//setting up file name with it's original extension using path module
      file.filename + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

//Multer file upload settings
const maxSize = 10 * 1024 * 1024;
const compressFileUpload = multer({
  storage,
  limits: {
    filesize: maxSize,
  },
});

//home route
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

//Compress route
app.post("/compress", compressFileUpload.array("file", 100), (req, res) => {

//Initializing adm-zip library
    const zip = new admzip();

//Checking for the files uploaded
    if (req.files) {
        req.files.map(file => {
            zip.addLocalFile(file.path);
        });

//creating zip file if there's none using fs module
        const output = Date.now() + "output.zip";
        fs.writeFileSync(output, zip.toBuffer());
        
//Downloading the compressed file
        res.download(output);
    }
});

app.listen(process.env.PORT || 5000, () => {
  console.log("server running on PORT 5000...");
});

Here, we’ve set up the Multer and ADM Zip library. This is it for backend.

Setting up Front-end –

Now, let’s create a front-end to actually upload files to our server and it’s super easy.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>ZIP Compressor</title>
  </head>
  <body>
    <div class="container">
      <h1 class="text-center">Compress Files to ZIP File</h1>
      <form action="/compress" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label for="file">Upload Files:</label>
          <input
            class="form-control"
            type="file"
            name="file"
            multiple
            required
          />
        </div>
        <div class="form-group">
          <button class="btn btn-block btn-primary">Download ZIP File</button>
        </div>
      </form>
    </div>
  </body>
</html>

This is a really simple HTML document, and I am keeping it super simple by using Bootstrap to do the basic styling.

The important part here is the form element, it’s important to have attribute action=”/compress” which states the route we need to make the post request to.

Also, the attribute enctype should be “multipart/form-data”, it helps us to upload files to the server.

Now, we need to add an input element so that we can choose the files that we want to upload. Make sure it has type=”file” and multiple attributes.

That’s it, that’s how easy it is to create a zip file compressor using Node and Express. I hope this post was helpful.

Let us know in the comments if it was.

Pawan Sargar
Follow him
```html ```

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *