### Install JSZip with component Source: https://stuk.github.io/jszip Install JSZip using the component package manager. ```bash component install Stuk/jszip ``` -------------------------------- ### Install Project Dependencies Source: https://stuk.github.io/jszip/documentation/contributing.html Install project dependencies using npm. This is the first step before building the project. ```bash npm install ``` -------------------------------- ### Install JSZip with bower Source: https://stuk.github.io/jszip Install JSZip using Bower, a package manager for the web. ```bash bower install Stuk/jszip ``` -------------------------------- ### Serve Documentation Locally Source: https://stuk.github.io/jszip/documentation/contributing.html Render the project documentation locally using Jekyll. Requires Jekyll installation. ```bash jekyll serve --baseurl '' ``` -------------------------------- ### Install JSZip with npm Source: https://stuk.github.io/jszip Install JSZip using npm for use in your Node.js projects or front-end build processes. ```bash npm install jszip ``` -------------------------------- ### generateAsync Basic Usage Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Basic examples demonstrating how to use generateAsync with different output types and for saving or downloading the zip file. ```APIDOC ## Basic Usage Examples ### Description Examples demonstrating the use of `generateAsync` with different `type` options and how to handle the resulting content, such as saving it to a file or creating a data URL. ### Method `generateAsync` ### Parameters #### Request Body - **type** (string) - Optional - The type of the output. Can be 'blob', 'base64', 'uint8array', 'arraybuffer', 'nodebuffer', or 'string'. Defaults to 'string'. ### Request Example 1 (Blob for FileSaver.js) ```javascript zip.generateAsync({type:"blob"}) .then(function (content) { // see FileSaver.js saveAs(content, "hello.zip"); }); ``` ### Request Example 2 (Base64 for Data URL) ```javascript zip.generateAsync({type:"base64"}) .then(function (content) { location.href="data:application/zip;base64,"+content; }); ``` ### Request Example 3 (Node Buffer for File System) ```javascript zip.folder("folder_1").folder("folder_2").file("hello.txt", "hello"); // zip now contains: // folder_1/ // folder_1/folder_2/ // folder_1/folder_2/hello.txt zip.folder("folder_1").generateAsync({type:"nodebuffer"}) .then(function (content) { // relative to folder_1/, this file only contains: // folder_2/ // folder_2/hello.txt require("fs").writeFile("hello.zip", content, function(err){/*...*/}); }); ``` ``` -------------------------------- ### Get Binary File with JSZipUtils Source: https://stuk.github.io/jszip/documentation/examples/get-binary-files-ajax.html Use JSZipUtils.getBinaryContent to fetch a zip file and then load it with JSZip. This is useful for older browsers or when a dedicated utility library is preferred. ```javascript "use strict"; // 1) get a promise of the content var promise = new JSZip.external.Promise(function (resolve, reject) { JSZipUtils.getBinaryContent("/jszip/test/ref/text.zip", function(err, data) { if (err) { reject(err); } else { resolve(data); } }); }); promise.then(JSZip.loadAsync) // 2) chain with the zip promise .then(function(zip) { return zip.file("Hello.txt").async("string"); // 3) chain with the text content promise }) .then(function success(text) { $("#jszip_utils").append($("

", { "class": "alert alert-success", text: "loaded, content = " + text })); }, function error(e) { $("#jszip_utils").append($("

", { "class": "alert alert-danger", text: e })); }); ``` ```html

``` -------------------------------- ### File ZipObject Example Source: https://stuk.github.io/jszip/documentation/api_zipobject.html Represents a file entry in a zip file, detailing its attributes such as name, type, date, comment, permissions, and compression method. ```json { name: 'docs/list.txt', dir: false, date: 2016-12-25T08:09:27.152Z, comment: null, unixPermissions: 33206, dosPermissions: null, options: { compression: 'DEFLATE', compressionOptions: null } } ``` -------------------------------- ### Directory ZipObject Example Source: https://stuk.github.io/jszip/documentation/api_zipobject.html Represents a directory entry in a zip file, showing its attributes including name, type, date, comment, permissions, and compression options. ```json { name: 'docs/', dir: true, date: 2016-12-25T08:09:27.153Z, comment: null, unixPermissions: 16877, dosPermissions: null, options: { compression: 'STORE', compressionOptions: null } } ``` -------------------------------- ### Get Binary File with Fetch API Source: https://stuk.github.io/jszip/documentation/examples/get-binary-files-ajax.html Utilize the modern Fetch API to retrieve a zip file as a blob, then process it with JSZip. This approach is suitable for modern browsers and offers a more promise-centric workflow. ```javascript "use strict"; fetch("/jszip/test/ref/text.zip") // 1) fetch the url .then(function (response) { if (response.status === 200 || response.status === 0) { return Promise.resolve(response.blob()); } else { return Promise.reject(new Error(response.statusText)); } }) .then(JSZip.loadAsync) // 3) chain with the zip promise .then(function (zip) { return zip.file("Hello.txt").async("string"); // 4) chain with the text content promise }) .then(function success(text) { $("#fetch").append($("

", { "class": "alert alert-success", text: "loaded, content = " + text })); }, function error(e) { $("#fetch").append($("

", { "class": "alert alert-danger", text: e })); }); ``` ```html

``` -------------------------------- ### Handle UTF-8 Encoded Files in JSZip Source: https://stuk.github.io/jszip/documentation/api_jszip/file_name.html This example demonstrates how to handle files with UTF-8 encoded content, such as currency symbols. You can read the content as a string or as raw binary data. ```javascript var zip = new JSZip(); zip.file("amount.txt", "€15"); zip.file("amount.txt").async("string") // a promise of "€15" zip.file("amount.txt").async("arraybuffer") // a promise of an ArrayBuffer containing €15 encoded as utf8 zip.file("amount.txt").async("uint8array") // a promise of an Uint8Array containing €15 encoded as utf8 ``` -------------------------------- ### Convert ZipObject text to string (2.x to 3.x) Source: https://stuk.github.io/jszip/documentation/upgrade_guide.html In JSZip v3, use `async('string')` instead of `asText()` to get file content as a string. This method returns a promise. ```javascript // 2.x zip.file("test.txt").asText(); // 3.x zip.file("test.txt").async("string") .then(function (content) { // use content }); ``` -------------------------------- ### Get file content as a string asynchronously Source: https://stuk.github.io/jszip/documentation/api_zipobject/async.html Use this to retrieve the file content as a plain string. Includes basic error handling for the Promise. ```javascript zip .file("my_text.txt") .async("string") .then(function success(content) { // use the content }, function error(e) { // handle the error }); ``` -------------------------------- ### Generate Zip from a Subfolder with Node.js Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Create a zip file containing only the contents of a specific subfolder. This example demonstrates generating a zip buffer from 'folder_1' and writing it to a file using Node.js `fs` module. ```javascript zip.folder("folder_1").folder("folder_2").file("hello.txt", "hello"); // zip now contains: // folder_1/ // folder_1/folder_2/ // folder_1/folder_2/hello.txt zip.folder("folder_1").generateAsync({type:"nodebuffer"}) .then(function (content) { // relative to folder_1/, this file only contains: // folder_2/ // folder_2/hello.txt require("fs").writeFile("hello.zip", content, function(err){/*...*/}); }); ``` -------------------------------- ### Get file content as base64 string (2.x to 3.x) Source: https://stuk.github.io/jszip/documentation/upgrade_guide.html In JSZip v3, use `async('base64')` to retrieve file content as a base64 encoded string. This replaces the older `asBinary()` combined with `JSZip.base64.encode()`. ```javascript // 2.x var data = zip.file("img.jpg").asBinary(); var dataURI = "data:image/jpeg;base64," + JSZip.base64.encode(data); // 3.x zip.file("img.jpg").async("base64") .then(function (data64) { var dataURI = "data:image/jpeg;base64," + data64; }); ``` -------------------------------- ### Get JSZip Version Source: https://stuk.github.io/jszip/documentation/api_jszip/version.html Access the JSZip.version property to get the library's version string. This is useful for checking compatibility or logging. ```javascript JSZip.version == "3.1.0"; ``` -------------------------------- ### Basic File Creation and Data Handling Source: https://stuk.github.io/jszip/documentation/api_jszip/file_data.html Create simple text files, files from Base64 strings, ArrayBuffers, or Node.js Buffers, and set custom dates. ```javascript zip.file("Hello.txt", "Hello World\n"); // base64 zip.file("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true}); // from an ajax call with xhr.responseType = 'arraybuffer' zip.file("smile.gif", arraybufferFromXhr); // or on nodejs zip.file("smile.gif", fs.readFileSync("smile.gif")); zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); zip.file("folder/file.txt", "file in folder"); zip.file("animals.txt", "dog,platypus\n").file("people.txt", "james,sebastian\n"); // result: // - Hello.txt // - smile.gif // - Xmas.txt // - animals.txt // - people.txt // - folder/ // - folder/file.txt ``` -------------------------------- ### Get ZipObject Content as Stream Source: https://stuk.github.io/jszip/documentation/api_zipobject/internal_stream.html Use internalStream to get the content of a file as a stream. Attach event listeners for 'data', 'error', and 'end' to handle the stream's lifecycle. The 'type' argument specifies the desired format of the data chunks. ```javascript zip .file("my_text.txt") .internalStream("string") .on("data", function (data) {...}) .on("error", function (e) {...}) .on("end", function () {...}); ``` -------------------------------- ### JSZip.loadAsync shortcut Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async_object.html Demonstrates the shortcut usage of JSZip.loadAsync for loading zip data. ```javascript var zip = new JSZip(); zip.loadAsync(data, options); ``` -------------------------------- ### Get file content as Uint8Array asynchronously Source: https://stuk.github.io/jszip/documentation/api_zipobject/async.html Use this when you need the file content as a Uint8Array. Ensure your browser supports this type. ```javascript zip.file("image.png").async("uint8array").then(function (u8) { // ... }); ``` -------------------------------- ### Create a JSZip Instance Source: https://stuk.github.io/jszip/documentation/examples.html Initialize a new JSZip object to manage zip archive contents. ```javascript var zip = new JSZip(); ``` -------------------------------- ### resume() Source: https://stuk.github.io/jszip/documentation/api_streamhelper/resume.html Resumes the stream if it is paused. Once resumed, the stream starts sending `data` events again. Returns the current StreamHelper object for chaining. ```APIDOC ## resume() ### Description Resume the stream if the stream is paused. Once resumed, the stream starts sending `data` events again. ### Returns The current StreamHelper object, for chaining. ### Since v3.0.0 ### Example ```javascript zip .generateInternalStream({type:"uint8array"}) .on('data', function() {...}) .resume(); ``` ``` -------------------------------- ### Build JSZip Project Source: https://stuk.github.io/jszip/documentation/contributing.html Generate the final and minified JSZip files in the dist/ directory. ```bash grunt ``` -------------------------------- ### generateAsync with mimeType option Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Example of generating a Blob with a custom mimeType, useful for specific file types like Open Document Spreadsheet. ```javascript // This example will Generate a Open Document Spreadsheet, with the correct mime type var zip = new JSZip(); zip.file("mimetype", "application/vnd.oasis.opendocument.spreadsheet"); var metaInf = zip.folder("META-INF"); metaInf.file("manifest.xml", "<..."); // ... // Generate the file zip.generateAsync({ type: "blob", mimeType: "application/ods", compression: "DEFLATE" }).then(function (odsFile) { // odsFile.type == "application/ods" }); ``` -------------------------------- ### Create a Folder in JSZip Source: https://stuk.github.io/jszip/documentation/api_jszip/folder_name.html Use `zip.folder()` to create a new directory. This method returns a new JSZip object with the new folder as its root, enabling chaining. ```javascript zip.folder("images"); ``` ```javascript zip.folder("css").file("style.css", "body {background: #FF0000}"); ``` ```javascript zip.file("css/font.css", "body {font-family: sans-serif}") ``` -------------------------------- ### Accumulate Stream Data with Callback Source: https://stuk.github.io/jszip/documentation/api_streamhelper/accumulate.html Use accumulate to get the full stream content as a Promise. An optional callback can be provided to receive progress updates. ```javascript zip .generateInternalStream({type:"uint8array"}) .accumulate(function updateCallback(metadata) { // metadata contains for example currentFile and percent, see the generateInternalStream doc. }).then(function (data) { // data contains here the complete zip file as a uint8array (the type asked in generateInternalStream) }); ``` -------------------------------- ### Run Browser Tests Source: https://stuk.github.io/jszip/documentation/contributing.html Execute the project tests in various browsers using SauceLabs. Requires a SauceLabs account and environment variables. ```bash npm run test-browser ``` -------------------------------- ### JSZip.loadAsync(data [, options]) Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async_object.html Loads a zip file asynchronously. This is a shortcut for creating a new JSZip instance and then calling loadAsync on it. It accepts data in various formats and optional configuration options. ```APIDOC ## JSZip.loadAsync(data [, options]) ### Description Loads a zip file asynchronously from various data formats. This method is a shortcut for instantiating JSZip and then calling `loadAsync` on the instance. ### Method Static method of the JSZip class. ### Parameters #### data - **data** (Blob|ArrayBuffer|string|Uint8Array|Buffer) - Required - The data of the zip file to load. Can be a Blob, ArrayBuffer, string, Uint8Array, or Node.js Buffer. #### options - **options** (Object) - Optional - Configuration options for loading the zip file. See the documentation for `JSZip.prototype.loadAsync` for available options. ### Examples Loading from a promise that resolves with zip data: ```javascript dataAsPromise.then(JSZip.loadAsync).then(function(zip) { // Process the zip file }); ``` Loading directly with data: ```javascript JSZip.loadAsync(dataAsPromise).then(function(zip) { // Process the zip file }); ``` ``` -------------------------------- ### Update Version and Publish Source: https://stuk.github.io/jszip/documentation/contributing.html Increment the project version using npm and publish the new release. ```bash npm version patch npm publish ``` -------------------------------- ### Create New JSZip Instance Source: https://stuk.github.io/jszip/documentation/api_jszip/constructor.html Instantiate a new JSZip object. This can be done using the `new` keyword or by directly calling the JSZip function. ```javascript var zip = new JSZip(); // same as var zip = JSZip(); ``` -------------------------------- ### Get File by Name in JSZip Source: https://stuk.github.io/jszip/documentation/api_jszip/file_name.html Use this to retrieve a file from the zip archive by its name. You can access its properties like name and dir, or asynchronously read its content. ```javascript var zip = new JSZip(); zip.file("file.txt", "content"); zip.file("file.txt").name // "file.txt" zip.file("file.txt").async("string") // a promise of "content" zip.file("file.txt").dir // false ``` -------------------------------- ### Run All Tests Source: https://stuk.github.io/jszip/documentation/contributing.html Execute tests in both Node.js and browser environments. ```bash npm run test ``` -------------------------------- ### Manually Include JSZip Source: https://stuk.github.io/jszip Include the JSZip library manually in your project by downloading the distribution file. ```html ``` -------------------------------- ### Get file content with progress updates Source: https://stuk.github.io/jszip/documentation/api_zipobject/async.html Provide an updateCallback function to monitor the progress of the asynchronous file extraction. The callback receives a metadata object with the completion percentage. ```javascript zip.file("image.png").async("uint8array", function updateCallback(metadata) { console.log("progression: " + metadata.percent.toFixed(2) + " %"); }).then(function (u8) { // ... }) ``` -------------------------------- ### Create and Populate a Zip File Source: https://stuk.github.io/jszip Use this snippet to create a new zip file, add text files, create folders, and add files to those folders. The zip file is then generated as a blob. ```javascript var zip = new JSZip(); zip.file("Hello.txt", "Hello World\n"); var img = zip.folder("images"); img.file("smile.gif", imgData, {base64: true}); zip.generateAsync({type:"blob"}) .then(function(content) { // see FileSaver.js saveAs(content, "example.zip"); }); ``` -------------------------------- ### Read zip file with JSZipUtils in browser (callback) Source: https://stuk.github.io/jszip/documentation/howto/read_zip.html Use JSZipUtils.getBinaryContent to fetch zip file data via AJAX and load it into JSZip using a callback. ```javascript JSZipUtils.getBinaryContent('path/to/content.zip', function(err, data) { if(err) { throw err; // or handle err } JSZip.loadAsync(data).then(function () { // ... }); }); ``` -------------------------------- ### JSZip Constructor Source: https://stuk.github.io/jszip/documentation/api_jszip/constructor.html Creates a new JSZip instance. This can be done using the `new` keyword or by calling the JSZip function directly. The instance returned is a new JSZip object. ```APIDOC ## new JSZip() or JSZip() ### Description Creates a new JSZip instance. This is the primary way to start working with the JSZip library to create or manipulate zip archives. ### Method Constructor/Function Call ### Parameters None ### Returns A new JSZip instance. ### Since v1.0.0 ### Example ```javascript // Using the constructor var zip = new JSZip(); // Calling the function directly (equivalent) var zip = JSZip(); ``` ``` -------------------------------- ### Load Zip and Create Folders Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async.html Set `createFolders: true` to automatically create all directory entries present in the zip file's path. Without this option, only virtual folders representing parts of file paths are created. ```javascript // here, "bin" is zip file containing: // folder1/folder2/folder3/file1.txt zip.loadAsync(bin) .then(function (zip) { console.log(zip.files); // folder1/folder2/folder3/file1.txt }); // with createFolders: true, all folders will be created zip.loadAsync(bin, {createFolders: true}) .then(function (zip) { console.log(zip.files); // folder1/ // folder1/folder2/ // folder1/folder2/folder3/ // folder1/folder2/folder3/file1.txt }); ``` -------------------------------- ### Custom File Name Encoding with JSZip Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Use the `encodeFileName` option to specify a custom encoding for file names. This example uses `iconv-lite` to encode file names with a specified encoding. Note that UTF-8 is the default and recommended encoding. ```javascript var iconv = require('iconv-lite'); zip.generateAsync({ type: 'uint8array', encodeFileName: function (string) { return iconv.encode(string, 'your-encoding'); } }); ``` -------------------------------- ### HTML Form for File Selection and Submission Source: https://stuk.github.io/jszip/documentation/examples/downloader.html This HTML structure defines the user interface for the downloader application. It includes a form with checkboxes for file selection, each with a data-url attribute specifying the file's source. A submit button initiates the zipping process, and elements for displaying progress and results are also included. Requires Bootstrap for styling. ```html

Please select your files

``` -------------------------------- ### Configure SauceLabs Credentials Source: https://stuk.github.io/jszip/documentation/contributing.html Set environment variables for SauceLabs username and access key on Linux systems. ```bash export SAUCE_USERNAME=your-saucelabs-username export SAUCE_ACCESS_KEY=your-saucelabs-access-key ``` -------------------------------- ### Loading zip data from a promise Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async_object.html Shows how to load zip data asynchronously using a promise. The promise should resolve with the zip file content. ```javascript dataAsPromise .then(JSZip.loadAsync) .then(function(zip) {...}) ``` -------------------------------- ### Marking an Entry as a Directory Source: https://stuk.github.io/jszip/documentation/api_jszip/file_data.html Create an entry that represents a directory. The content is ignored when the 'dir' option is true. ```javascript zip.file("folder/", null, { dir: true }); ``` -------------------------------- ### forEach(callback) Source: https://stuk.github.io/jszip/documentation/api_jszip/for_each.html Iterates over all files and folders at the current directory level, executing a provided callback function for each entry. The callback receives the relative path and the ZipObject for each item. ```APIDOC ## forEach(callback) ### Description Call a callback function for each entry at this folder level. ### Arguments - **callback** (function) - The callback function to execute for each entry. It has the signature `function(relativePath, file)`. - **relativePath** (string) - The filename and its path, relative to the current folder. - **file** (ZipObject) - The current file or folder object. ### Returns Nothing. ### Since v3.0.0 ### Examples ```javascript var zip = new JSZip(); zip.file("package.json", "..."); zip.file("lib/index.js", "..."); zip.file("test/index.html", "..."); zip.file("test/asserts/file.js", "..."); zip.file("test/asserts/generate.js", "..."); zip.folder("test").forEach(function (relativePath, file){ console.log("iterating over", relativePath); }); // will display: // iterating over index.html // iterating over asserts/ // iterating over asserts/file.js // iterating over asserts/generate.js ``` ``` -------------------------------- ### Load zip archive data (2.x to 3.x) Source: https://stuk.github.io/jszip/documentation/upgrade_guide.html JSZip v3 replaces the constructor with data and `load()` with `loadAsync()`, which returns a promise. ```javascript // 2.x new JSZip(data); zip.load(data); // zip.file(...) // 3.x JSZip.loadAsync(data).then(zip) {...}; zip.loadAsync(data).then(zip) {...}; // here, zip won't have (yet) the updated content ``` -------------------------------- ### Streaming Files with JSZip Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Enable `streamFiles: true` to use less memory by streaming file content and data descriptors. Be aware that some programs may not support data descriptors. ```javascript zip.generateAsync({ type: 'uint8array', streamFiles: true }); ``` -------------------------------- ### Add local file to zip in Node.js (promises) Source: https://stuk.github.io/jszip/documentation/howto/read_zip.html Read a local file using Node.js 'fs' module and add it to a new JSZip instance using Promises. ```javascript var contentPromise = new JSZip.external.Promise(function (resolve, reject) { fs.readFile("picture.png", function(err, data) { if (err) { reject(e); } else { resolve(data); } }); }); zip.file("picture.png", contentPromise); ``` -------------------------------- ### Add file with binary data Source: https://stuk.github.io/jszip/documentation/api_jszip/file_data.html Use the `binary: true` option when the data should be treated as raw binary content. This is important for binary strings that may contain non-UTF-8 characters. ```javascript var zip = new JSZip(); // here, we have a correct (unicode) string zip.file("hello.txt", "unicode ♥", {binary: false}); // here, we have a binary string: it can contain binary content, one byte // per character. zip.file("hello.txt", "unicode \xE2\x99\xA5", {binary: true}); ``` -------------------------------- ### Read zip file with JSZipUtils in browser (promises) Source: https://stuk.github.io/jszip/documentation/howto/read_zip.html Fetch zip file data via AJAX using JSZipUtils and load it into JSZip using Promises. ```javascript new JSZip.external.Promise(function (resolve, reject) { JSZipUtils.getBinaryContent('path/to/content.zip', function(err, data) { if (err) { reject(err); } else { resolve(data); } }); }).then(function (data) { return JSZip.loadAsync(data); }) .then(...) ``` -------------------------------- ### Replace JSZip Promise Implementation Source: https://stuk.github.io/jszip/documentation/api_jszip/external.html Shows how to replace the default Promise implementation used by JSZip. This is useful for integrating with specific Promise libraries like Bluebird or using the native Promise object. ```javascript // use bluebird instead JSZip.external.Promise = Bluebird; // use the native Promise object: JSZip.external.Promise = Promise; ``` -------------------------------- ### Setting Compression for Individual Files Source: https://stuk.github.io/jszip/documentation/api_jszip/file_data.html Override the global compression settings for specific files. Use 'STORE' to disable compression or 'DEFLATE' with a specific level. ```javascript zip.file("a.png", contentOfA, { compression: "STORE" // force a compression for this file }); zip.file("b.txt", contentOfA, { compression: "DEFLATE", compressionOptions: { level: 9 // force a compression and a compression level for this file } }); // don't force anything, use the generateAsync options zip.file("c.txt", contentOfB); // here: // - a.png will not be compressed (STORE) // - b.txt will be compressed at maximum level // - c.txt will be compressed with the default compression level zip.generateAsync({ type: "blob", compression: "DEFLATE" }); ``` -------------------------------- ### HTML for File Input and Content Display Source: https://stuk.github.io/jszip/documentation/examples/read-local-file-api.html This HTML sets up a file input for selecting local zip files and a designated area to display the extracted content. It includes a note about file size limitations. ```html

Choose the local(s) zip file(s)

Note : your browser will process the zip file, don't choose a file too big !


``` -------------------------------- ### Access Files in Nested Folders with JSZip Source: https://stuk.github.io/jszip/documentation/api_jszip/file_name.html Demonstrates how to create and access files within subfolders using JSZip. You can specify the path with forward slashes or by chaining folder() and file() methods. ```javascript // with folders zip.folder("sub").file("file.txt", "content"); zip.file("sub/file.txt"); // the file // or zip.folder("sub").file("file.txt") // the file ``` -------------------------------- ### JSZip File Method Source: https://stuk.github.io/jszip/documentation/api_jszip/file_data.html The `file(name, data [,options])` method adds or updates a file in the zip archive. It returns the JSZip object for chaining. ```APIDOC ## file(name, data [,options]) ### Description Add (or update) a file to the zip file. If something goes wrong (the data is not in a supported format for example), an exception will be propagated when accessing the data. ### Returns The current JSZip object, for chaining. ### Arguments #### name - **name** (string) - Required - The name of the file. You can specify folders in the name : the folder separator is a forward slash (“/”). #### data - **data** (String/ArrayBuffer/Uint8Array/Buffer/Blob/Promise/Nodejs stream) - Required - The content of the file. #### options - **options** (object) - Optional - The options for the file. ### Options Details #### base64 - **base64** (boolean) - Optional - `false` - Set to `true` if the data is base64 encoded. For example image data from a `` element. Plain text and HTML do not need this option. #### binary - **binary** (boolean) - Optional - `false` - Set to `true` if the data should be treated as raw content, `false` if this is a text. If base64 is true, this defaults to `true`. If the data is not a string, this will be set to `true`. #### date - **date** (date) - Optional - The current date - The last modification date. #### compression - **compression** (string) - Optional - `null` - If set, specifies compression method to use for this specific file. If not, the default file compression will be used. #### compressionOptions - **compressionOptions** (object) - Optional - `null` - The options to use when compressing the file. #### comment - **comment** (string) - Optional - `null` - The comment for this file. #### optimizedBinaryString - **optimizedBinaryString** (boolean) - Optional - `false` - Set to true if (and only if) the input is a “binary string” and has already been prepared with a 0xFF mask. #### createFolders - **createFolders** (boolean) - Optional - `true` - Set to true if folders in the file path should be automatically created, otherwise there will only be virtual folders that represent the path to the file. #### unixPermissions - **unixPermissions** (16 bits number) - Optional - `null` - The UNIX permissions of the file, if any. #### dosPermissions - **dosPermissions** (6 bits number) - Optional - `null` - The DOS permissions of the file, if any. #### dir - **dir** (boolean) - Optional - `false` - Set to true if this is a directory and content should be ignored. ### Data Input Considerations - **Data Mutability**: You shouldn’t update the data given to this method: it is kept as it so any update will impact the stored data. - **Promise Support (since v3.0.0)**: You can use a Promise of content directly to simplify async content handling. - **Blob Support (since v3.0.0)**: You can use Blob directly as input, no need to use a `FileReader`. File objects are Blobs so you can use them directly. - **Node.js Stream Support (since v3.0.0)**: A stream can’t be restarted; if it is used once, it can’t be used again. In that case, the promise/stream will get an error. ### Examples #### Using Promises ```javascript // instead of $.get("url/to.file.txt") // jQuery v3 returns promises .then(function (content) { zip.file("file.txt", content); }) // you can do var promise = $.get("url/to.file.txt"); zip.file("file.txt", promise); ``` #### Using Callbacks with Promises ```javascript var promise = new Promise(function (resolve, reject) { request('url/to.file.txt', function (error, response, body) { if (error) { reject(error); } else { resolve(body); } }); }); zip.file("file.txt", promise); ``` #### Using Blob ```javascript // in a change callback of a var files = evt.target.files; for (var i = 0; i < files.length; i++) { var f = files[i]; zip.file(f.name, f); } ``` #### Using `base64` option ```javascript var zip = new JSZip(); zip.file("hello.txt", "aGVsbG8gd29ybGQK", {base64: true}); ``` #### Using `binary` option ```javascript var zip = new JSZip(); // here, we have a correct (unicode) string zip.file("hello.txt", "unicode ♥", {binary: false}); // here, we have a binary string: it can contain binary content, one byte // per character. zip.file("hello.txt", "unicode \xE2\x99\xA5", {binary: true}); ``` #### Using `date` option ```javascript zip.file("Xmas.txt", "Ho ho ho !", { date: new Date("December 25, 2007 00:00:01") }); ``` ``` -------------------------------- ### JavaScript Helper Functions for UI Updates Source: https://stuk.github.io/jszip/documentation/examples/downloader.html Provides utility functions to manage user feedback, including resetting messages, displaying success or error alerts, and updating a progress bar. These functions are essential for providing a clear user experience during the download and zipping process. Assumes the presence of corresponding HTML elements with specific IDs. ```javascript "use strict"; /** * Reset the message. */ function resetMessage () { $("#result") .removeClass() .text(""); } /** * show a successful message. * @param {String} text the text to show. */ // eslint-disable-next-line no-unused-vars function showMessage(text) { resetMessage(); $("#result") .addClass("alert alert-success") .text(text); } /** * show an error message. * @param {String} text the text to show. */ function showError(text) { resetMessage(); $("#result") .addClass("alert alert-danger") .text(text); } /** * Update the progress bar. * @param {Integer} percent the current percent */ // eslint-disable-next-line no-unused-vars function updatePercent(percent) { $("#progress_bar").removeClass("hide") .find(".progress-bar") .attr("aria-valuenow", percent) .css({ width : percent + "%" }); } if(!JSZip.support.blob) { showError("This demo works only with a recent browser !"); } ``` -------------------------------- ### Generate zip archive (2.x to 3.x) Source: https://stuk.github.io/jszip/documentation/upgrade_guide.html JSZip v3 replaces `generate()` with `generateAsync()` for asynchronous archive generation. The `type` option is now mandatory. ```javascript // 2.x zip.generate(); // 3.x zip.generateAsync({type:"uint8array"}) .then(function (content) { // use content }); ``` -------------------------------- ### Add local file to zip in Node.js (callback) Source: https://stuk.github.io/jszip/documentation/howto/read_zip.html Read a local file using Node.js 'fs' module and add it to a new JSZip instance using a callback. ```javascript // 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); }); ``` -------------------------------- ### Generate zip as Node.js stream and save to file Source: https://stuk.github.io/jszip/documentation/howto/write_zip.html In a Node.js environment, generate zip files as Node.js Buffers and pipe them to a writable stream for saving to disk. This is efficient for large zip files. ```javascript 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."); }); ``` -------------------------------- ### Add and Update Files in JSZip Source: https://stuk.github.io/jszip/documentation/examples.html Add new files or update existing ones within the zip archive. The `.file()` method can be chained for convenience. ```javascript // create a file zip.file("hello.txt", "Hello[p my)6cxsw2q"); // oops, cat on keyboard. Fixing ! zip.file("hello.txt", "Hello World\n"); ``` -------------------------------- ### generateAsync Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Generates the complete zip file at the current folder level. It returns a Promise of the generated zip file. An error will be propagated if the asked `type` is not available in the browser. ```APIDOC ## generateAsync(options[, onUpdate]) ### Description Generates the complete zip file at the current folder level. ### Method Asynchronous (returns a Promise) ### Parameters #### Options - **options** (object) - Required - The options to generate the zip file. - **options.type** (string) - Required - The type of zip to return. Possible values: `base64`, `binarystring`, `string` (deprecated), `array`, `uint8array`, `arraybuffer`, `blob`, `nodebuffer`. - **options.compression** (string) - Optional - The default file compression method to use. Default: `STORE` (no compression). Available: `STORE`, `DEFLATE`. - **options.compressionOptions** (object) - Optional - The options to use when compressing the file. Default: `null`. For `DEFLATE`, can include `level` (1-9). - **options.comment** (string) - Optional - The comment to use for the zip file. - **options.mimeType** (string) - Optional - Mime-type for the generated file. Default: `application/zip`. - **options.platform** (string) - Optional - The platform to use when generating the zip file. Default: `DOS`. Possible values: `DOS`, `UNIX`, or nodejs `process.platform` values. - **options.encodeFileName** (function) - Optional - The function to encode the file name / comment. Default: encode with UTF-8. - **options.streamFiles** (boolean) - Optional - Stream the files and create file descriptors. Default: `false`. - **onUpdate** (function) - Optional - The optional function called on each internal update with the metadata. ### Response - **Promise** - A Promise that resolves with the generated zip file in the specified type. ``` -------------------------------- ### Read zip file in Node.js (callback) Source: https://stuk.github.io/jszip/documentation/howto/read_zip.html Read a local zip file using Node.js 'fs' module and load it into JSZip using a callback. ```javascript "use strict"; var fs = require("fs"); var JSZip = require("jszip"); // read a zip file fs.readFile("test.zip", function(err, data) { if (err) throw err; JSZip.loadAsync(data).then(function (zip) { // ... }); }); ``` -------------------------------- ### Generate Zip as Base64 and Download Source: https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html Generate a zip file as a Base64 encoded string and set the browser's location to a data URL for direct download. ```javascript zip.generateAsync({type:"base64"}) .then(function (content) { location.href="data:application/zip;base64,"+content; }); ``` -------------------------------- ### Read zip file in Node.js (promises) Source: https://stuk.github.io/jszip/documentation/howto/read_zip.html Read a local zip file using Node.js 'fs' module and load it into JSZip using Promises. ```javascript new JSZip.external.Promise(function (resolve, reject) { fs.readFile("test.zip", function(err, data) { if (err) { reject(e); } else { resolve(data); } }); }).then(function (data) { return JSZip.loadAsync(data); }) .then(...) ``` -------------------------------- ### Directly loading zip data from a promise Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async_object.html An alternative way to load zip data directly from a promise, passing the promise as an argument to JSZip.loadAsync. ```javascript JSZip.loadAsync(dataAsPromise) .then(function(zip) {...}) ``` -------------------------------- ### loadAsync(data [, options]) Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async.html Reads an existing zip file and merges its data into the current JSZip object. If the JSZip object already contains entries, new entries will be merged, and entries with the same name will be replaced. Since v3.8.0, relative path components are sanitized to prevent zip slip attacks. The method returns a Promise that resolves with the updated zip object or rejects if the data is invalid or uses unsupported features. ```APIDOC ## loadAsync(data [, options]) ### Description Reads an existing zip file and merges its data into the current JSZip object. If the JSZip object already contains entries, new entries will be merged, and entries with the same name will be replaced. Since v3.8.0, relative path components are sanitized to prevent zip slip attacks. The method returns a Promise that resolves with the updated zip object or rejects if the data is invalid or uses unsupported features. ### Method loadAsync ### Parameters #### Arguments - **data** (String/Array of bytes/ArrayBuffer/Uint8Array/Buffer/Blob/Promise) - Required - The zip file data. - **options** (object) - Optional - Configuration options for loading the zip file. #### Options - **base64** (boolean) - Optional - Defaults to `false`. Set to `true` if the data is base64 encoded. - **checkCRC32** (boolean) - Optional - Defaults to `false`. Set to `true` to verify CRC32 checksums. - **optimizedBinaryString** (boolean) - Optional - Defaults to `false`. Set to `true` if the input is a string and has already been prepared with a 0xFF mask. - **createFolders** (boolean) - Optional - Defaults to `false`. Set to `true` to automatically create folders in the file path. - **decodeFileName** (function) - Optional - Defaults to UTF-8 decoding. A function to decode file names and comments. ### Returns A Promise that resolves with the updated JSZip object or rejects with an error. ### Supported Zip Features - Compression (DEFLATE) - ZIP with data descriptor - ZIP64 - UTF8 in file name and content ### Unsupported Zip Features - Password protected zip - Multi-volume zip ### Example - Base64 Encoding ```javascript var zip = new JSZip(); zip.loadAsync("UEsDBAoDAAAAAJxs8T...AAAAAA==", {base64: true}); ``` ### Example - Check CRC32 ```javascript // Assuming 'bin' is a corrupted zip file zip.loadAsync(bin) .then(function (zip) { // This will be called even if content is corrupted }, function (e) { // This will not be called }); zip.loadAsync(bin, { checkCRC32: true }) .then(function (zip) { // This will not be called }, function (e) { // Error: Corrupted zip : CRC32 mismatch }); ``` ### Example - Create Folders ```javascript // Assuming 'bin' is a zip file containing: folder1/folder2/folder3/file1.txt zip.loadAsync(bin) .then(function (zip) { console.log(zip.files); // Output: folder1/folder2/folder3/file1.txt }); // With createFolders: true zip.loadAsync(bin, {createFolders: true}) .then(function (zip) { console.log(zip.files); // Output: // folder1/ // folder1/folder2/ // folder1/folder2/folder3/ // folder1/folder2/folder3/file1.txt }); ``` ### Example - Decode File Name ```javascript // Assuming 'bin' is a Russian zip file using cp866 encoding for file names // Default UTF-8 decoding might lead to wrong file names: zip.loadAsync(bin) .then(function (zip) { console.log(zip.files); // Example output: ' / ⥪⮢ 㬥.txt' }); // Using the correct encoding with iconv-lite: var iconv = require('iconv-lite'); zip.loadAsync(bin, { decodeFileName: function (bytes) { return iconv.decode(bytes, 'cp866'); } }) .then(function (zip) { console.log(zip.files); // Example output: 'Новая папка/Новый текстовый документ.txt' }); ``` ``` -------------------------------- ### Clone JSZip Repository Source: https://stuk.github.io/jszip/documentation/contributing.html Clone the JSZip source code from GitHub using Git. ```bash git clone https://github.com/Stuk/jszip.git ``` -------------------------------- ### Load Zip with Relative Filename Resolution Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async.html Load a zip file and observe how JSZip resolves relative paths (e.g., 'src/images/../file.txt' becomes 'src/file.txt') and handles directory traversal attempts (e.g., '../../example.txt' is resolved correctly). Access the original unsafe name via `unsafeOriginalName`. ```javascript // here, "unsafe.zip" is zip file containing: // src/images/../file.txt // ../../example.txt require("fs").readFile("unsafe.zip", function (err, data) { if (err) throw err; var zip = new JSZip(); zip.loadAsync(data) .then(function (zip) { console.log(zip.files); // src/file.txt // example.txt console.log(zip.files["example.txt"].unsafeOriginalName); // "../../example.txt" }); } ``` -------------------------------- ### Load Zip with Base64 Encoding Source: https://stuk.github.io/jszip/documentation/api_jszip/load_async.html Use the `base64: true` option when the zip data is provided as a base64 encoded string. ```javascript var zip = new JSZip(); zip.loadAsync("UEsDBAoDAAAAAJxs8T...AAAAAA==", {base64: true}); ```