Fork me on GitHub

zip.js

Core API

Contents

  1. Configuration
  2. I/O
  3. Zip reading
  4. Zip reading example
  5. Zip writing
  6. Zip writing example
  7. Full example
  8. Alternative DEFLATE implementations
  9. Concatenating worker scripts

  1. Configuration

    Configuration options can only be set after loading zip.js.

    zip.js uses Web workers to compress and uncompress data in non-blocking background processes. If you need to disable Web workers, set zip.useWebWorkers to false (you must also import deflate.js and/or inflate.js in the web page).

    When zip.js uses Web workers it needs to know the locations of worker scripts. By default, the worker scripts are loaded from the directory of the page's base URL, but this can be overridden by the workerScriptsPath or workerScripts options. Only of of them can be set, not both.

    • zip.workerScriptsPath: the URL to the directory containing the default worker scripts (z-worker.js, deflate.js, and inflate.js). If a relative URL is specified, it is resolved against the page's base URL (usually the URL of the web page importing zip.js). Example:

      zip.workerScriptsPath = '<zip_js_dir>/';
    • zip.workerScripts: an advanced option to explicitly control which scripts are loaded in the web worker. workerScripts.deflater and workerScripts.inflater should be arrays of URLs to scripts for deflater/inflater, respectively. All URLs are resolved relative to the page's base URL. Scripts in the array are executed in order, and the first one should be z-worker.js, which is used to start the worker. Example:

      zip.workerScripts = {
        deflater: ['<zip_js_dir>/z-worker.js', '<zip_js_dir>/deflate.js'],
        inflater: ['<zip_js_dir>/z-worker.js', '<zip_js_dir>/inflate.js']
      };

    If only deflation or inflation is use in your application, the unused workerScripts.deflater/inflater properties can be omitted, and the unused deflate.js/inflate.js file can be removed.

    Normally the option zip.workerScriptsPath is enough. However if you want to use alternative deflate implementations, or want to concatenate worker scripts, zip.workerScripts can be useful, see below.

  2. I/O

    Reader and Writer constructors

    zip.js can handle multiple types of data thanks to a generic API. This feature is based on 2 abstract constructors: zip.Reader and zip.Writer.
    zip.Reader constructors help to read data from a file and zip.Writer constructors help to write data into a file.

    For example, if you need to read a zip and store its file into a variable, you must use a zip.Reader object to read the compressed zip data. You must also use a zip.Writer object to write uncompressed file data into the variable.

    Reader constructors

    zip.TextReader(text)

    string reader constructor

    Parameters:

    text (string)
    The string to read

    zip.BlobReader(blob)

    Blob object reader constructor

    Parameters:

    blob (Blob)
    The Blob object to read

    zip.Data64URIReader(dataURI)

    Data URI reader constructor

    Parameters:

    dataURI (string)
    The data URI to read

    zip.HttpReader(URL)

    HTTP content reader constructor

    Parameters:

    URL (string)
    The URL of the content to read

    zip.HttpRangeReader(URL)

    HTTP content reader using "Range" request header constructor

    Parameters:

    URL (string)
    The URL of the content to read

    Reader members (used internally)

    Attributes:

    size (number)
    The uncompressed data byte size

    Methods:

    zip.Reader.prototype.init(callback, onerror)

    Initialize the zip.Reader object.

    Parameters:

    success callback (Function)
    callback function
    onerror (Function)
    error callback function
    zip.Reader.prototype.readUint8Array(index, length, callback[, onerror])

    Extract an UInt8Array object beginning at index location through the specified length.

    Parameters:

    index (number)
    The beginning index
    length (number)
    The UInt8Array object length
    callback (Function)
    success callback function returning the UInt8Array object as parameter
    onerror (Function)
    error callback function

    Writer constructors

    zip.TextWriter()

    string writer constructor


    zip.BlobWriter()

    Blob object writer constructor


    zip.FileWriter(fileEntry)

    File object writer constructor

    Parameters:

    fileEntry (FileEntry)
    the FileEntry object used to write the File object

    zip.Data64URIWriter([mimeString])

    Data URI writer constructor

    Parameters:

    mimeString (string)
    the data MIME type

    Writer members (used internally)

    Methods:

    zip.Writer.prototype.init(callback[, onerror])

    Initialize the zip.Writer object.

    Parameters:

    callback (Function)
    callback function
    zip.Writer.prototype.writeUint8Array(array, callback[, onerror])

    Write an UInt8Array object at the current index.

    Parameters:

    array (UInt8Array)
    The UInt8Array to write
    callback (Function)
    success callback function
    onerror (Function)
    error callback function
    zip.Writer.prototype.getData(callback[, onerror])

    Get written data (returned type depends on zip.Reader constructor used)

    Parameters:

    callback (Function)
    success callback function returning the data as parameter
    onerror (Function)
    error callback function
  3. Zip reading

    initialization

    zip.createReader(reader, callback[, onerror])

    Create a ZipReader object. A ZipReader object helps to read the zipped content.

    Parameters:

    reader (zip.Reader)
    the zip.Reader object used to read input data
    callback (Function)
    success callback function returning the new ZipReader object as parameter
    onerror (Function)
    global error callback function

    Zip entries listing

    ZipReader.prototype.getEntries(callback)

    Get all entries from a zip.

    Parameters:

    callback (Function)
    callback function returning the Array of Entry object as parameter

    Zip entry data reading

    Entry()

    Constructor representing a zip file entry.

    Attributes:

    filename (string)
    file name
    directory (boolean)
    true if the entry is a directory
    compressedSize (number)
    compressed data size
    uncompressedSize (number)
    uncompressed data size
    lastModDate (Date)
    last modification date
    lastModDateRaw (number)
    last modification date in raw format (MS-DOS)
    comment (string)
    file comment
    crc32 (number)
    uncompressed data checksum

    Methods:

    Entry.prototype.getData(writer, onend[, onprogress, checkCrc32])

    Get the data of a zip entry.

    Parameters:

    writer (zip.Writer)
    zip.Writer object used to write output data
    onend (Function)
    success callback function returning the output data (returned type depends on zip.Writer constructor used) as parameter
    onprogress (Function)
    progress callback function returning the progress index (number) and a max value (number) as parameters
    checkCrc32 (boolean)
    pass true to verify data integrity

    Zip closing

    ZipReader.prototype.close(callback)

    Close the opened zip file and immediately terminate the associated web worker(s). When close() is not called, the worker(s) may still be terminated when the reader is garbage-collected.

    Parameters:

    callback (Function)
    success callback function
  4. Zip reading example

    Read a zip from a Blob/File object

    // use a BlobReader to read the zip from a Blob object
    zip.createReader(new zip.BlobReader(blob), function(reader) {
    
      // get all entries from the zip
      reader.getEntries(function(entries) {
        if (entries.length) {
    
          // get first entry content as text
          entries[0].getData(new zip.TextWriter(), function(text) {
            // text contains the entry data as a String
            console.log(text);
    
            // close the zip reader
            reader.close(function() {
              // onclose callback
            });
    
          }, function(current, total) {
            // onprogress callback
          });
        }
      });
    }, function(error) {
      // onerror callback
    });
  5. Zip writing

    initialization

    zip.createWriter(writer, callback[, onerror[, dontDeflate]])

    Create a ZipWriter object.

    Parameters:

    writer (zip.Writer)
    the zip.Writer object used to write output data
    callback (Function)
    success callback function returning the new ZipWriter object as parameter
    onerror (Function)
    global error callback function
    dontDeflate (Boolean)
    whether or not to use deflate

    Zip entry writing

    ZipWriter.prototype.add(name, reader, onend[, onprogress, options])

    Add a new entry into the zip.

    Parameters:

    name (string)
    entry file name
    reader (zip.Reader)
    the zip.Reader object used to read entry data to add - null for directory entry
    onend (Function)
    success callback function
    onprogress (Function)
    progress callback function returning the progress index (number) and a max value (number) as parameters
    options (Object)
    entry options properties:
    directory (boolean)
    true if the entry is a directory
    level (number)
    compression level from 0 to 9
    comment (string)
    file comment
    lastModDate (Date)
    last modification date
    version (number)
    zip version

    Zip closing

    ZipWriter.prototype.close(callback)

    Close the opened zip and terminate the associated web worker(s).

    Parameters:

    callback (Function)
    success callback function returning the generated zip data (returned type depends on zip.Writer constructor used) as parameter
  6. Zip writing example

    Write a zip into a Blob object

    // use a BlobWriter to store the zip into a Blob object
    zip.createWriter(new zip.BlobWriter(), function(writer) {
    
      // use a TextReader to read the String to add
      writer.add("filename.txt", new zip.TextReader("test!"), function() {
        // onsuccess callback
    
        // close the zip writer
        writer.close(function(blob) {
          // blob contains the zip file as a Blob object
    
        });
      }, function(currentIndex, totalIndex) {
        // onprogress callback
      });
    }, function(error) {
      // onerror callback
    });
  7. Full example

    // create the blob object storing the data to compress
    var blob = new Blob([ "Lorem ipsum dolor sit amet, consectetuer adipiscing elit..." ], {
      type : "text/plain"
    });
    // creates a zip storing the file "lorem.txt" with blob as data
    // the zip will be stored into a Blob object (zippedBlob)
    zipBlob("lorem.txt", blob, function(zippedBlob) {
      // unzip the first file from zipped data stored in zippedBlob
      unzipBlob(zippedBlob, function(unzippedBlob) {
        // logs the uncompressed Blob
        console.log(unzippedBlob);
      });
    });
    
    function zipBlob(filename, blob, callback) {
      // use a zip.BlobWriter object to write zipped data into a Blob object
      zip.createWriter(new zip.BlobWriter("application/zip"), function(zipWriter) {
        // use a BlobReader object to read the data stored into blob variable
        zipWriter.add(filename, new zip.BlobReader(blob), function() {
          // close the writer and calls callback function
          zipWriter.close(callback);
        });
      }, onerror);
    }
    
    function unzipBlob(blob, callback) {
      // use a zip.BlobReader object to read zipped data stored into blob variable
      zip.createReader(new zip.BlobReader(blob), function(zipReader) {
        // get entries from the zip file
        zipReader.getEntries(function(entries) {
          // get data from the first file
          entries[0].getData(new zip.BlobWriter("text/plain"), function(data) {
            // close the reader and calls callback function with uncompressed data as parameter
            zipReader.close();
            callback(data);
          });
        });
      }, onerror);
    }
    
    function onerror(message) {
      console.error(message);
    }
  8. Alternative DEFLATE implementations

    Alternative DEFLATE implementations can be used with zip.js in favor of better performance and/or better compliance. Currently zlib-asm and pako are supported. In order to use them, you need to set the zip.workerScripts option instead of the zip.workerScriptsPath option, see below.

    • zlib-asm

      zlib-asm is produced by compiling C code of zlib to asm.js with Emscripten. Because zlib is regarded as one of the reference implementation of DEFLATE algorithm, the compatibility of zlib-asm should be very good. If the browser supports asm.js (e.g. Firefox), zlib-asm can deliver amazing performance, especially when inflating files. To use zlib-asm with zip.js, put file zlib.js from zlib-asm in <zlib-asm_dir>, and configure zip.js as follows:

      zip.workerScripts = {
        deflater: ['<zip_js_dir>/z-worker.js', '<zlib-asm_dir>/zlib.js', '<zip_js_dir>/zlib-asm/codecs.js'],
        inflater: ['<zip_js_dir>/z-worker.js', '<zlib-asm_dir>/zlib.js', '<zip_js_dir>/zlib-asm/codecs.js']
      };

      '<zip_js_dir>/z-worker.js' is the entry script of the worker, and '<zip_js_dir>/zlib-asm/codecs.js' is the wrapper of zlib-asm. These two files can be found in zip.js project. File 'zlib.js' is a part of zlib-asm project , and is not provided by zip.js. You can find it here. The latest version of zlib-asm tested with zip.js is v0.2.2.

    • Pako

      Pako is a hand-writing javascript port of zlib. Its compatibility and performance is believed to be good. The major advantage of pako over zlib-asm may be that its code size is much smaller (45KB vs 193KB). To use pako in worker, configure zip.js as follow:

      zip.workerScripts = {
        deflater: ['<zip_js_dir>/z-worker.js', '<pako_dir>/pako.min.js', '<zip_js_dir>/pako/codecs.js'],
        inflater: ['<zip_js_dir>/z-worker.js', '<pako_dir>/pako.min.js', '<zip_js_dir>/pako/codecs.js']
      };

      Pako also has separate js files for deflating/inflating, you can also use them instead of 'pako.min.js':

      zip.workerScripts = {
        deflater: ['<zip_js_dir>/z-worker.js', '<pako_dir>/pako_deflate.min.js', '<zip_js_dir>/pako/codecs.js'],
        inflater: ['<zip_js_dir>/z-worker.js', '<pako_dir>/pako_inflate.min.js', '<zip_js_dir>/pako/codecs.js']
      };

      '<zip_js_dir>/z-worker.js' is the entry script of the worker, and '<zip_js_dir>/pako/codecs.js' is the wrapper of pako. These two files can be found in zip.js project. Note that 'pako.min.js' etc. are parts of pako project, and are not provided by zip.js. You can find them here. The latest version of pako tested with zip.js is 0.2.5.

  9. Concatenating worker scripts

    Worker scripts can also be concatenated to reduce the number of HTTP requests. You are free to choose files to concatenate, just make sure the resulting files containing z-worker.js are loaded first in workers, and necessary deflater/inflater/wrapper files are included. Examples:

    zip.workerScripts = {
      deflater: ['<some_dir>/worker_deflate.js'], // z-worker.js + deflate.js
      inflater: ['<some_dir>/worker_inflate.js'], // z-worker.js + inflate.js
    };
    
    zip.workerScripts = {
      deflater: ['<some_dir>/worker_asm.js', '<zlib-asm_dir>/zlib.js'], // worker_asm.js = z-worker.js + zlib-asm/codecs.js
      inflater: ['<some_dir>/worker_asm.js', '<zlib-asm_dir>/zlib.js'],
    };
    
    zip.workerScripts = {
      deflater: ['<some_dir>/worker_pako.js'], // z-worker.js + pako/codecs.js + pako.min.js
      inflater: ['<some_dir>/worker_pako.js'],
    };