Ticker

6/recent/ticker-posts

JSZip

JSZip

JSZip is a javascript library for creating, reading and editing .zip files, with a lovely and simple API.

Installation

With npm : npm install jszip

With bower : bower install Stuk/jszip

Manually : manually load JS file download.

Import the dependency within the component that requires it.

JSZip

import JSZip from 'jszip';
or
import * as JSZip from 'jszip';

var zip = new JSZip(); 


we can add (and update) files and folders with .file(name, content) and .folder(name). They return the current JSZip instance so you can chain the calls.

// create a file

zip.file("hello.txt", "Hello word");

zip.file("hello.txt", "Hello World\n");

 

// create a file and a folder

zip.folder("test");

zip.file("nested/hello.txt", "Hello World\n");

 

// same as

zip.folder("nested").file("hello.txt", "Hello World\n");

 

var test= zip.folder("test");

test.file("test.txt", "a folder with photos");  

 

You can access the file content with.

zip.file("hello.txt").async("string").then(function (data) {

  // data is "Hello World\n"

});


if (JSZip.support.uint8array) {

  zip.file("hello.txt").async("uint8array").then(function (data) {

    // data is Uint8Array { 0=72, 1=101, 2=108, more...}

  });


You can also remove files or folders with .remove(name)

zip.remove("test/test");

zip.remove("test");

// same as

zip.remove("test"); // by removing the folder, you also remove its content. 


Generate a zip file 

With .generateAsync(options) or .generateNodeStream(options) you can generate a zip file (not a real file but its representation in memory). Check this page for more information on how to write / give the file to the user.

var promise = null;

if (JSZip.support.uint8array) {

  promise = zip.generateAsync({type : "uint8array"});

} else {

  promise = zip.generateAsync({type : "string"});

}

Read a zip file

With .loadAsync(data) you can load a zip file. Check this page to see how to do properly (it’s more tricky that it seems).

var new_zip = new JSZip();

// more files !

new_zip.loadAsync(content)

.then(function(zip) {

    // you now have every files contained in the loaded zip

    zip.file("hello.txt").async("string"); // a promise of "Hello World\n"

});