JSZip
repository·main·Indexed 27 days ago
https://github.com/stuk/jszipA lightweight JavaScript library for creating, reading, and editing .zip files. JSZip allows developers to programmatically build zip archives, manage folder structures, and export content as blobs, base64 strings, Node.js buffers, and other formats. Version 3.10.1.
What's inside jszip
- JSZip is a JavaScript library designed for creating, reading, and editing .zip files. It provides a simple API for managing file structures and generating zip archives in various formats.
Download a ZIP file in the browser using Blob URL / FileSaver
mainFor modern browsers, the most efficient way to provide a ZIP file to a user is to generate the ZIP as a
bloband use thesaveAsfunction from FileSaver.js. This utilizes the nativesaveAsAPI in Chrome/IE10+ or a Blob URL in Firefox.zip.generateAsync({type:"blob"}) .then(function (blob) { saveAs(blob, "hello.zip"); });Migrate from JSZip 1.x to 2.x
mainSignificant changes occurred in the transition from 1.x to 2.x:
- Renaming:
JSZipBase64was renamed toJSZip.base64. - Data Access: The
.dataattribute was removed. Use getters like.asText()or.asBinary()instead. - Compression/Decompression: Use the
compressInputTypeanduncompressInputTypeattributes to specify input types.
// before zip.file("test.txt").data; zip.files["test.txt"].data; zip.file("image.png").data; zip.files["image.png"].data; // after zip.file("test.txt").asText(); zip.files["test.txt"].asText(); zip.file("image.png").asBinary(); zip.files["image.png"].asBinary();- Renaming:
Use streamFiles to reduce memory usage
mainBy default,
options.streamFilesisfalse. JSZip holds the processed file in memory to ensure the CRC32 and size are placed correctly at the start of the entry, making the zip compatible with all programs.If you set
options.streamFiles: true, JSZip will stream the files and use data descriptors at the end of the entry. This uses significantly less memory but may result in zip files that some programs cannot read.zip.generateAsync({ type: 'uint8array', streamFiles: true });Read a remote ZIP file in Node.js
mainWhen downloading a ZIP file in Node.js to use with JSZip, it is critical to ensure the data is treated as binary.
- If using the built-in
httpmodule: Do not set an encoding on the response, or set it tonull. Collect chunks into an array and useBuffer.concat(data)to create a single Buffer. - If using the
requestlibrary: Setencoding: nullin the request options to ensure the body is returned as a Buffer.
// Example using the 'request' library "use strict"; var request = require('request'); var JSZip = require("jszip"); request({ method : "GET", url : "http://localhost/.../file.zip", encoding: null // <- this one is important! }, function (error, response, body) { if(error || response.statusCode !== 200) { // handle error return; } JSZip.loadAsync(body).then(function (zip) { return zip.file("content.txt").async("string"); }).then(function (text) { console.log(text); }); });- If using the built-in
Add files to a ZIP in Node.js
mainYou can add files to a
JSZipinstance in Node.js using several methods:- Using a Buffer: Pass the file data directly to
zip.file(name, data). - Using a Promise: Pass a promise that resolves to the file data to
zip.file(name, promise). - Using a Stream: Pass a readable stream directly to
zip.file(name, stream).
// read a file and add it to a zip fs.readFile("picture.png", function(err, data) { if (err) throw err; var zip = new JSZip(); zip.file("picture.png", data); }); // or using a promise var contentPromise = new JSZip.external.Promise(function (resolve, reject) { fs.readFile("picture.png", function(err, data) { if (err) { reject(err); } else { resolve(data); } }); }); zip.file("picture.png", contentPromise); // read a file as a stream and add it to a zip var stream = fs.createReadStream("picture.png"); zip.file("picture.png", stream);- Using a Buffer: Pass the file data directly to
Read a ZIP file in the browser via AJAX
mainTo load a ZIP file from a remote URL in the browser, it is recommended to use
JSZipUtils.getBinaryContentfrom thejszip-utilslibrary. This handles the complexities of binary data retrieval across different browsers.If you are implementing a custom solution using
XMLHttpRequest:- For modern browsers (Firefox/Chrome/Opera), set the mime type:
xhr.overrideMimeType("text/plain; charset=x-user-defined");. - For browsers supporting XHR2, set the
responseTypeto"arraybuffer"to receive anArrayBufferdirectly.
JSZipUtils.getBinaryContent('path/to/content.zip', function(err, data) { if(err) { throw err; // or handle err } JSZip.loadAsync(data).then(function () { // ... }); });- For modern browsers (Firefox/Chrome/Opera), set the mime type:
Download a ZIP file in the browser using Downloadify
mainIf you use Downloadify (which uses a Flash SWF), you can pass a ZIP file by generating it as
base64and setting thedataTypeoption to'base64'.zip = new JSZip(); zip.file("Hello.", "hello.txt"); zip.generateAsync({type:"base64"}).then(function (base64) { Downloadify.create('downloadify',{ ... data: function(){ return base64; }, ... dataType: 'base64' }); });Write a ZIP file to disk in Node.js using Streams
mainIn a Node.js environment, you can use
generateNodeStreamwith{type: 'nodebuffer', streamFiles: true}to create a readable stream. This stream can be piped directly into a filesystem writable stream (e.g.,fs.createWriteStream).var fs = require("fs"); var JSZip = require("jszip"); var zip = new JSZip(); // zip.file("file", content); // ... and other manipulations zip .generateNodeStream({type:'nodebuffer',streamFiles:true}) .pipe(fs.createWriteStream('out.zip')) .on('finish', function () { // JSZip generates a readable stream with a "end" event, // but is piped here in a writable stream which emits a "finish" event. console.log("out.zip written."); });Migrate from JSZip 2.2.2 to 2.3.0
mainIn version 2.3.0, several attributes were moved from
ZipObject#optionsdirectly onto theZipObjectitself.Changes:
zip.file("name").options.date$\rightarrow$zip.file("name").datezip.file("name").options.dir$\rightarrow$zip.file("name").dirzip.file("name").options.base64andzip.file("name").options.binaryare deprecated.
Also Deprecated:
JSZip.base64JSZip.prototype.crc32JSZip.prototype.utf8decodeandJSZip.prototype.utf8encodeJSZip.utils
// deprecated zip.file("test.txt").options.date zip.file("test.txt").options.dir // new API zip.file("test.txt").date zip.file("test.txt").dirDownload a ZIP file in the browser using Data URI
mainIn older browsers that support data URI, you can generate the ZIP as a
base64string and assign it tolocation.href.Warning: This method has inconsistent filename support across browsers (e.g., Firefox may append
.partextensions, and Safari may name the fileUnknown).zip.generateAsync({type:"base64"}).then(function (base64) { location.href="data:application/zip;base64," + base64; });Handle performance and memory issues in JSZip
mainJSZip holds the full result in memory when using
async()andgenerateAsync(). To avoid browser crashes or memory exhaustion with large files, follow these best practices:- Use Typed Arrays: Always prefer
Uint8Array,ArrayBuffer, orBlobover strings.- When generating a zip, use
type: "uint8array"(orblob,arraybuffer,nodebuffer). - When loading files via AJAX/XHR, request an
ArrayBufferinstead of a string.
- When generating a zip, use
- Avoid Older Browsers: Do not use Internet Explorer 9 or below, as they lack typed array support and will suffer significant performance penalties during compression.
- Stream Large Files: If the result is too large for memory and you cannot use
nodeStreamorgenerateNodeStream, use the underlyingStreamHelperto process data chunk by chunk, utilizingpause()andresume()to manage backpressure.
- Use Typed Arrays: Always prefer