JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

How to Create Zip files with Node.js

--

Photo by Viktor Talashuk on Unsplash

Here we are into looking at how to create zip files with Node.js using the JSZIP library.

Create the project

  • Create a new folder and open the command terminal inside it.
  • Type npm init -y to initialize the project.
  • Install the package with npm i jszip command.
  • Create app.js file inside the project folder.

This is the sample project I have created.

Project structure

Here we have a PDF file as “sample.pdf” and two images (“coding-science.jpg” and “programming-languages.jpg”). And the goal is to make a zip file consisting of a folder that contains two images, a PDF, and generated text file.

Zip folder structure

Implementation

We can do this with a few lines of code.

  • First, we read the local PDF using the readFileSync method and add it to the zip.
  • Next, we generate a sample text file with some text with the following code.
zip.file("Textfile.txt", "Hello NodeJS\n");
  • Then we create a folder “images” with the following line.
const img = zip.folder("images");
  • And we can add two images using a loop to the folder as below.
for (const image of images) {
const imageData = fs.readFileSync(image);
img.file(image, imageData);
}
  • Finally, we can generate and output the zip folder created.

Let’s run and verify the code. Type following to run the program.

node app.js

Then you will see the sample.zip file has been created inside your project folder like below.

Project folder after zip file generation

This is the zip folder. We have the images folder, PDF file, and text file inside it.

Zip folder

And the images folder contains two images.

images folder

That’s it. Note that JSZIP is not only for Node.js. It can be used with frontend frameworks like Angular as well.

You can find the working example here.

Hope you enjoyed this. Happy coding!

👉 Node.js’ versatility goes beyond just creating zip files. Learn how to create an AI-based command line chat app with Node.js here:

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

No responses yet