zip.js

Core API

Contents

  1. Installation
  2. Configuration
  3. Input/output classes
  4. ZipReader class
  5. ZipReader example
  6. ZipWriter class
  7. ZipWriter example
  8. Full example
  9. Alternative DEFLATE implementations

Installation

Configuration

You can call the function zip.configure in order to configure zip.js. It accepts a configuration object as parameter with these optional properties:

useWebWorkers (boolean)
Enables the use of Web workers to compress and uncompress data in non-blocking background processes. The default value is true.
terminateWorkerTimeout (number)
Delay before terminating a web worker in ms. The default value is 5000. You can call zip.terminateWorkers() to terminate idle workers.
maxWorkers (number)
Number of workers used simultaneously to process data. The default value is the number of logical cores returned by the attribute navigator.hardwareConcurrency or 2 if navigator is undefined.
workerScripts (Object)
Advanced option to explicitly control which scripts are loaded in the web worker. It allows using alternative deflate implementations or specifying a URL to the worker script if the CSP of the page blocks scripts imported with a Blob URL.
The properties deflate and inflate must specify arrays of URLs to import the deflate/inflate scripts, respectively. The first URL is relative to the base URI of the document. The other URLs are relative to the URL of the first script. Scripts in the array are executed in order. If only deflation or inflation is used in your application, the unused workerScripts.deflate/inflate property can be omitted. Example:
zip.configure({
  workerScripts: {
    deflate: ["library_path/custom-worker.js", "./custom-deflate.js"],
    inflate: ["library_path/custom-worker.js", "./custom-inflate.js"]
  }
});
You can use this property if the CSP of the page blocks scripts imported with a Blob URL. For this, you have to add z-worker.js from the /dist directory in your project and specify the URL where it can be found in your project. Example:
zip.configure({
  workerScripts: {
    deflate: ["library_path/z-worker.js"],
    inflate: ["library_path/z-worker.js"]
  }
});

Input/output classes

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. The zip.Reader constructors help to read data from a source of data. The zip.Writer constructors help to write data into a destination.

For example, if you need to read a zip and store a uncompressed 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 the uncompressed file data into the variable.

Reader constructors

string reader constructor

zip.TextReader(text)

Parameters:

text (string)
The string to read

Blob object reader constructor

zip.BlobReader(blob)

Parameters:

blob (Blob)
The Blob object to read

Uint8Array object reader constructor

zip.Uint8ArrayReader(array)

Parameters:

array (Uint8Array)
The Uint8Array array to read

Data URI reader constructor

zip.Data64URIReader(dataURI)

Parameters:

dataURI (string)
The data URI to read

HTTP content reader constructor

zip.HttpReader(URL [, options])

Parameters:

URL (string)
The URL of the content to read
options (Object)
Optional properties:
useRangeHeader (boolean)
boolean value specifying if the Range request header should be used (false by default)
preventHeadRequest (boolean)
boolean value specifying if a HEAD request can be sent in order the get the content length (false by default)
forceRangeRequests (boolean)
boolean value specifying if the Range request header should be sent even if the server does not send responses with the header Accept-Ranges: bytes (false by default)
useXHR (boolean)
boolean value specifying if the implementation should rely on the XMLHttpRequest API instead of the fetch API to send requests (false by default)
If useXHR is not set to true, you can additionnally pass any option the fetch API accepts.

HTTP content reader using Range request header constructor

zip.HttpRangeReader(URL [, options])

Parameters:

URL (string)
The URL of the content to read
options (Object)
Optional properties:
forceRangeRequests (boolean)
boolean value specifying if the Range request header should be sent even if the server does not send responses with the header Accept-Ranges: bytes (false by default)
useXHR (boolean)
boolean value specifying if the implementation should rely on the XMLHttpRequest API instead of the fetch API to send requests (false by default)
If useXHR is not set to true, you can additionnally pass any option the fetch API accepts.

Reader members (used internally)

Attributes

size (number)
The size of data to read in bytes

Methods

zip.Reader#init()

Initialize the zip.Reader object

Returns:

Promise
A promise with undefined as resolved value

zip.Reader#readUint8Array(index, length])

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

Parameters:

index (number)
The beginning index
length (number)
The UInt8Array object length

Returns:

Promise
A promise with the UInt8Array object as resolved value

Writer constructors

string writer constructor

zip.TextWriter()

Blob object writer constructor

zip.BlobWriter([mimeString])

Parameters:

mimeString (string)
The MIME type of the data to write

Uint8Array object writer constructor

zip.Uint8ArrayWriter()

Data URI writer constructor

zip.Data64URIWriter([mimeString])

Parameters:

mimeString (string)
The MIME type of the data to write

Writer members (used internally)

Attributes

size (number)
The size of written data in bytes

Methods

zip.Writer#init()

Initialize the zip.Writer object

Returns:

Promise
A promise with undefined as resolved value

zip.Writer#writeUint8Array(array)

Write an UInt8Array object at the current index

Parameters:

array (UInt8Array)
The UInt8Array to write

Returns:

Promise
A promise with undefined as resolved value

zip.Writer#getData()

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

Returns:

Promise
A promise with the data as resolved value

ZipReader class

Constructor

zip.ZipReader(reader [, options])

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
options (Object)
Optional properties:
checkSignature (boolean)
boolean value specifying if the signature of all the files should be verified (false by default)
password (string)
password used to decrypt all the files (undefined by default)
filenameEncoding (string)
encoding of filenames stored in another encoding than UTF-8 (cp437 by default)
commentEncoding (string)
encoding of comments stored in another encoding than UTF-8 (cp437 by default)
useWebWorkers (boolean)
boolean value specifying if web workers should be used (undefined by default)
signal (AbortSignal)
signal object created with an AbortController instance and used to cancel the decompression

Methods

zip.ZipReader#getEntries([options])

Get all entries from a zip.

Parameters:

options (Object)
Optional properties:
onprogress (Function)
function tracking the task progress and having as parameters an index (number) value, a max (number) value (undefined by default) and the file entry
filenameEncoding (string)
encoding of filenames stored in another encoding than UTF-8 (cp437 by default)
commentEncoding (string)
encoding of comments stored in another encoding than UTF-8 (cp437 by default)

Returns:

Promise
A promise with the Array of Entry objects as resolved value

zip.ZipReader#close()

Close the opened zip file.

Returns:

Promise
A promise with undefined as resolved value

Entry class

Entry()

Constructor representing a zip file entry

Attributes

filename (string)
file name
rawFilename (UInt8Array)
file name in binary format
filenameUTF8 (boolean)
true if the filename is encoded in UTF-8
directory (boolean)
true if the entry is a directory
encrypted (boolean)
true if the entry is encrypted
compressedSize (number)
compressed data size
uncompressedSize (number)
uncompressed data size
lastModDate (Date)
last modification date
lastAccessDate (Date)
last access date (current date by default)
creationDate (Date)
creation date (current date by default)
rawLastModDate (number)
last modification date in binary format (MS-DOS)
comment (string)
file comment
rawComment (UInt8Array)
file comment in binary format
commentUTF8 (boolean)
true if the comment is encoded in UTF-8
extraField (Map)
Map of extra field data where the key (number) is the type of the extra field and the value is a UInt8Array
rawExtraField (UInt8Array)
extra field in binary format
signature (Number or UInt8Array)
signature (crc checksum or AES authentication code) of the file
zip64 (boolean)
true if the file is formatted in Zip64
compressionMethod (number)
compression method

Methods

Entry#getData(writer [, options])

Get the data of a zip entry

Parameters:

writer (zip.Writer)
The zip.Writer object used to write output data
options (Object)
Optional properties:
onprogress (Function)
function tracking the task progress and having as parameters an index (number) value and a max (number) value (undefined by default)
checkSignature (boolean)
boolean value specifying if the signature of the file should be verified (false by default)
password (string)
password used to decrypt the file encrypted with AES or ZipCrypto (undefined by default)
useWebWorkers (boolean)
boolean value specifying if web workers should be used (undefined by default)

Returns:

Promise
A promise with the output data (returned type depends on zip.Writer constructor used) as resolved value

ZipReader example

Read a zip from a Blob/File object

// create a BlobReader to read with a ZipReader the zip from a Blob object
const reader = new zip.ZipReader(new zip.BlobReader(blob));

// get all entries from the zip
const entries = await reader.getEntries();
if (entries.length) {

  // get first entry content as text by using a TextWriter
  const text = await entries[0].getData(
    // writer
    new zip.TextWriter(),
    // options
    { 
      onprogress: (index, max) => {
         // onprogress callback
      }
    }
  );
  // text contains the entry data as a String
  console.log(text);

}

// close the ZipReader
await reader.close();

ZipWriter class

Constructor

zip.ZipWriter(writer [, options])

Create a ZipWriter object

Parameters:

writer (zip.Writer)
The zip.Writer object used to write output data
options (Object)
Optional properties:
zip64 (boolean)
force all the files to be written in Zip64 (false by default)
level (number)
compression level applied on all files (5 by default)
bufferedWrite (boolean)
true to explicitely allow calling ZipWriter#add multiple times in parallel (false by default)
keepOrder (boolean)
true to keep the files in order when calling ZipWriter#add multiple times in parallel (true by default)
lastModDate (Date)
last modification date of all files (current date by default)
extendedTimestamp (boolean)
use extended timestamp and ntfs extra fields (true by default)
lastAccessDate (Date)
last access date of all files (current date by default)
creationDate (Date)
creation date of all files (current date by default)
version (number)
zip version of all files (undefined by default)
versionMadeBy (number)
"version made by" field of all files (29 by default)
password (string)
password used to encrypt all the files (undefined by default)
encryptionStrength (number)
strength of the encryption algorithm: 1 for AES-128, 2 for AES-192, 3 for AES-256 (3 by default)
zipCrypto (boolean)
use ZipCrypto instead of AES (false by default)
useWebWorkers (boolean)
boolean value specifying if web workers should be used (undefined by default)
dataDescriptor (boolean)
boolean value specifying the data descriptor record should be included (true by default)
signal (AbortSignal)
signal object created with an AbortController instance and used to cancel the compression
internalFileAttribute (number)
internal file attribute of all files (undefined by default)
externalFileAttribute (number)
external file attribute of all files (undefined by default)

Methods

zip.ZipWriter#add(name , reader [, 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
options (Object)
Optional properties:
onprogress (Function)
function tracking the task progress and having as parameters an index (number) value and a max (number) value (undefined by default)
directory (boolean)
true if the entry is a directory (undefined by default)
level (number)
compression level from 0 (no compression) to 9 (max. compression) (5 by default)
bufferedWrite (boolean)
true to explicitely allow calling ZipWriter#add multiple times in parallel (false by default)
keepOrder (boolean)
true to keep the files in order when calling ZipWriter#add multiple times in parallel (true by default)
comment (string)
file comment (undefined by default)
lastModDate (Date)
last modification date (current date by default)
extendedTimestamp (boolean)
use extended timestamp and ntfs extra fields (true by default)
lastAccessDate (Date)
last access date (current date by default)
creationDate (Date)
creation date (current date by default)
version (number)
zip version (undefined by default)
versionMadeBy (number)
"version made by" field (29 by default)
password (string)
password used to encrypt the file with AES or ZipCrypto (undefined by default)
encryptionStrength (number)
strength of the encryption algorithm: 1 for AES-128, 2 for AES-192, 3 for AES-256 (3 by default)
zipCrypto (boolean)
use ZipCrypto instead of AES (false by default)
zip64 (boolean)
force the file entry to be written in Zip64 (undefined by default)
extraField (Map)
Map of extra field data where the key (number) is the type of the extra field and the value is a UInt8Array (undefined by default)
useWebWorkers (boolean)
boolean value specifying if web workers should be used (undefined by default)
dataDescriptor (boolean)
boolean value specifying the data descriptor record should be included (true by default)
signal (AbortSignal)
signal object created with an AbortController instance and used to cancel the compression
internalFileAttribute (number)
internal file attribute (undefined by default)
externalFileAttribute (number)
external file attribute (undefined by default)

Returns:

Promise
A promise with an Entry object as resolved value

zip.ZipWriter#close([comment], [options])

Close the zip file

Parameters:

comment (UInt8Array)
A comment to add at the end of the zip file
options (Object)
Optional properties:
onprogress (Function)
function tracking the task progress and having as parameters an index (number) value, a max (number) value (undefined by default) and the file entry
zip64 (boolean)
force the file entry to be written in Zip64 (undefined by default)

Returns:

Promise
A promise with the value of writer.getData() as resolved value

ZipWriter example

Write a zip into a Blob object

// use a BlobWriter to store with a ZipWriter the zip into a Blob object
const blobWriter = new zip.BlobWriter("application/zip");
const writer = new zip.ZipWriter(blobWriter);

// use a TextReader to read the String to add
await writer.add("filename.txt", new zip.TextReader("test!"));

// close the ZipReader
await writer.close();

// get the zip file as a Blob
const blob = await blobWriter.getData();

Full example

// - create the inputBlob object storing the data to compress
const inputBlob = new Blob(
  ["Lorem ipsum dolor sit amet, consectetuer adipiscing elit..."], 
  { type: "text/plain" });

// - create a Data64URIWriter object to write the zipped data into a data URI
// - create a ZipWriter object with the Data64URIWriter object as parameter
const zipWriter = new zip.ZipWriter(new zip.Data64URIWriter("application/zip"));

// - create a BlobReader object to read the content of inputBlob
// - add a new file named "text.txt" in the zip and associate it to the BlobReader object
await zipWriter.add("test.txt", new zip.BlobReader(inputBlob));

// - close the ZipWriter object and get compressed data
const dataURI = await zipWriter.close();
// - log compressed data
console.log(dataURI);
// data:application/zip;base64,UEsDBBQACAgIAJuFO1IAAAAAAAAAAAAAAAAIAAAAdGVzdC50e...


// - create a Data64URIReader object with the zipped content 
// - create a ZipReader object to read the zipped data
const zipReader = new zip.ZipReader(new zip.Data64URIReader(dataURI));

// - get entries from the zip file
const entries = await zipReader.getEntries();

// - use a TextWriter object to write the unzipped data of the first entry into a string
const data = await entries[0].getData(new zip.TextWriter());
// - close the ZipReader object
await zipReader.close();

// - log data
console.log(data);
// Lorem ipsum dolor sit amet, consectetuer adipiscing elit...

You can find some other examples of code in the /tests and the /demos directories of the project.

Alternative DEFLATE implementations

Alternative DEFLATE implementations can be used with zip.js in favor of better performance and/or better compliance.