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. GitHub - Kanchana46/nodejs-zip *You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…*github.co
Hope you enjoyed this. Happy coding!.