Compressing files can be a convenient way to optimize storage and transfer of data. In this blog post, we will learn how to zip files in JavaScript using a library called JSZip.
Setting up the environment
First, we need to install the JSZip library. You can either include it using a <script>
tag for a browser-based project or install it using npm for a Node.js project.
For a browser-based project, include the following script tag in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.5.0/jszip.min.js"></script>
For a Node.js project, install JSZip using npm:
npm install jszip
Creating a Zip File
Now that we have JSZip installed, let’s create a zip file containing some text files. The following example demonstrates how to create a zip file containing two text files:
const JSZip = require('jszip'); const zip = new JSZip(); zip.file('file1.txt', 'Hello, World!'); zip.file('file2.txt', 'This is another text file.'); zip.generateAsync({type: 'blob'}) .then(function (content) { // Do something with the zipped content, like saving it to disk });In the example above, we first require the JSZip library (skip this step for browser-based projects). We then create a new instance of JSZip, add two text files to it, and finally generate a zip file asynchronously as a Blob.
Saving the Zip File
Once we have created the zip file, we might want to save it to disk or offer it for download. Here’s how you can do that in a browser environment:
function saveAs(blob, filename) { const anchor = document.createElement('a'); const url = URL.createObjectURL(blob); anchor.href = url; anchor.download = filename; document.body.appendChild(anchor); anchor.click(); setTimeout(function() { document.body.removeChild(anchor); URL.revokeObjectURL(url); }, 100); } zip.generateAsync({type: 'blob'}) .then(function (content) { saveAs(content, 'my-files.zip'); });In the example above, we define a saveAs function that creates a temporary anchor element with the generated Blob URL and triggers a download by simulating a click event. The zip file will be downloaded with the specified filename.
Conclusion
In this blog post, we learned how to zip files in JavaScript using the JSZip library. We covered how to create a zip file containing text files and how to save the zip file in a browser environment. JSZip offers many more features, such as adding binary files, folders, and even zipping/unzipping entire directories. You can explore the official JSZip documentation to learn more about its capabilities.