Working with ZIP Archives in TypeScript: JSZip Library and Practical Examples
In modern web development, there is often a need to package multiple files into a single archive for convenient downloading or data transfer. In the TypeScript (and JavaScript) ecosystem, the most popular solution for working with ZIP archives is the JSZip library. It allows you to create, read, and modify ZIP files both in the browser and in the Node.js environment.
In this article, we will thoroughly cover the installation, configuration, and main usage scenarios of JSZip in TypeScript projects. You will learn how to create archives from strings, binary data, and entire folders, as well as extract the contents of existing ZIP files.
Installing and Importing JSZip
To get started, install the library and its types via npm or yarn:
npm install jszipnpm install --save-dev @types/jszipAfter installation, import JSZip into your TypeScript file:
import JSZip from 'jszip';If you are using a module system (ES modules), the import will work as shown above. For CommonJS (require), the syntax may differ, but in TypeScript projects, it is recommended to use ES imports.
Creating a New ZIP Archive
The simplest scenario is to create an archive and add several text files to it. Let's look at an example:
const zip = new JSZip();
// Add text fileszip.file("hello.txt", "Hello, World!");zip.file("readme.md", "# Documentation
This is an example Markdown file.");
// Add a folder and a file inside itconst folder = zip.folder("images");folder.file("logo.png", "base64encodedstring...", {base64: true});
// Generate the ZIP file as a Blobzip.generateAsync({type: "blob"}).then((content) => { // Create a download link const link = document.createElement("a"); link.href = URL.createObjectURL(content); link.download = "my-archive.zip"; link.click();});In this example, we:
- Created a
JSZipinstance - Added two text files using the
.file()method - Created a nested folder
imagesand placed a file with base64 data inside it - Generated the archive in Blob format and initiated a download
Reading and Extracting an Existing ZIP Archive
JSZip allows you not only to create but also to read archives. This is done using the loadAsync() method:
async function readZipFile(zipBlob: Blob): Promise<void> { try { const zip = await JSZip.loadAsync(zipBlob); // Get the list of all files const fileNames = Object.keys(zip.files); console.log("Files in archive:", fileNames);
// Extract the contents of a specific file const helloFile = zip.file("hello.txt"); if (helloFile) { const content = await helloFile.async("string"); console.log("Contents of hello.txt:", content); }
// Iterate over all files zip.forEach((relativePath, zipEntry) => { console.log(`Found file: ${relativePath}, size: ${zipEntry._data.uncompressedSize} bytes`); });
} catch (error) { console.error("Error reading ZIP:", error); }}Note the typing: JSZip.loadAsync() returns a promise that resolves to a JSZip object. The .file() method returns JSZipObject | null, so you need to check the file's existence before calling .async().
Working with Binary Data and Images
Often, you need to package images or other binary files into an archive. JSZip supports working with ArrayBuffer, Blob, Uint8Array, and base64:
// Adding a file from ArrayBu