npm install @zip.js/zip.js
Then, you can import it as a JavaScript module in your project and bundle it with your favorite
tools:
import
import * as zip from "@zip.js/zip.js";
require
const zip = require("@zip.js/zip.js");
zip.min.js
from the
/dist
directory in your project. If you don't want to use web workers, add
zip-full.min.js
instead. Then, include zip.min.js
(or
zip-full.min.js
) in your HTML page:
<script type="text/javascript" src="/library_path/zip.min.js"></script>
<script>
// the zip API is in window.zip
// ...
</script>
require(["/library_path/zip.min.js"], zip => {
// ...
});
useWebWorkers
set to false
zip.configure({
useWebWorkers: false
});
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)
true
.
terminateWorkerTimeout (number)
5000
. You can call
zip.terminateWorkers()
to terminate idle workers.
maxWorkers (number)
navigator.hardwareConcurrency
or 2
if navigator
is undefined
.
workerScripts (Object)
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"]
}
});
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.
string
reader constructor
zip.TextReader(text)
Parameters:
text (string)
string
to read
Blob
object reader constructor
zip.BlobReader(blob)
Parameters:
Uint8Array
object reader constructor
zip.Uint8ArrayReader(array)
Parameters:
array (Uint8Array)
Uint8Array
array to read
Data URI reader constructor
zip.Data64URIReader(dataURI)
Parameters:
dataURI (string)
HTTP content reader constructor
zip.HttpReader(URL [, options])
Parameters:
URL (string)
options (Object)
useRangeHeader (boolean)
Range
request header should be used
(false
by default)preventHeadRequest (boolean)
HEAD
request can be sent in order the get the content
length (false
by default)forceRangeRequests (boolean)
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)
XMLHttpRequest
API instead of the fetch
API to send
requests (false
by default)headers (Iterable or array of objects)
undefined
by default)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)
options (Object)
forceRangeRequests (boolean)
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)
XMLHttpRequest
API instead of the fetch
API to send
requests (false
by default)headers (Iterable or array of objects)
undefined
by default)useXHR
is not set to true
, you can additionnally pass any option the
fetch
API accepts.
size (number)
zip.Reader#init()
Initialize the zip.Reader
object
Returns:
Promise
undefined
as resolved valuezip.Reader#readUint8Array(index, length])
Extract an
UInt8Array
object beginning at index
location through the specified length
Parameters:
index (number)
length (number)
UInt8Array
object
length
Returns:
Promise
UInt8Array
object as resolved value
string
writer constructor
zip.TextWriter()
Blob
object writer constructor
zip.BlobWriter([mimeString])
Parameters:
mimeString (string)
Uint8Array
object writer constructor
zip.Uint8ArrayWriter()
Data URI writer constructor
zip.Data64URIWriter([mimeString])
Parameters:
mimeString (string)
size (number)
zip.Writer#init()
Initialize the zip.Writer
object
Returns:
Promise
undefined
as resolved valuezip.Writer#writeUint8Array(array)
Write an
UInt8Array
object at the current index
Parameters:
array (UInt8Array)
UInt8Array
to write
Returns:
Promise
undefined
as resolved valuezip.Writer#getData()
Get written data (returned type depends on zip.Reader
constructor
used)
Returns:
Promise
zip.ZipReader(reader [, options])
Create a ZipReader
object. A
ZipReader
object helps to read the zipped content.
Parameters:
reader (zip.Reader)
zip.Reader
object used to read input dataoptions (Object)
checkSignature (boolean)
false
by default)password (string)
undefined
by default)filenameEncoding (string)
cp437
by
default)commentEncoding (string)
cp437
by
default)useWebWorkers (boolean)
undefined
by default)signal (AbortSignal)
zip.ZipReader#getEntries([options])
Get all entries from a zip.
Parameters:
options (Object)
onprogress (Function)
index (number)
value, a max (number)
value (undefined
by default) and the file entry
filenameEncoding (string)
cp437
by
default)commentEncoding (string)
cp437
by
default)Returns:
Promise
Entry
objects as resolved valuezip.ZipReader#close()
Close the opened zip file.
Returns:
Promise
undefined
as resolved valueEntry()
Constructor representing a zip file entry
filename (string)
rawFilename (UInt8Array)
filenameUTF8 (boolean)
true
if the filename is encoded in UTF-8directory (boolean)
true
if the entry is a directoryencrypted (boolean)
true
if the entry is encryptedcompressedSize (number)
uncompressedSize (number)
lastModDate (Date)
lastAccessDate (Date)
creationDate (Date)
rawLastModDate (number)
comment (string)
rawComment (UInt8Array)
commentUTF8 (boolean)
true
if the comment is encoded in UTF-8extraField (Map)
(number)
is the type of the extra field and the value
is a UInt8Array
rawExtraField (UInt8Array)
signature (Number or UInt8Array)
zip64 (boolean)
true
if the file is formatted in Zip64compressionMethod (number)
Entry#getData(writer [, options])
Get the data of a zip entry
Parameters:
writer (zip.Writer)
zip.Writer
object used to write output dataoptions (Object)
onprogress (Function)
index (number)
value and a max (number)
value (undefined
by default)checkSignature (boolean)
false
by
default)password (string)
undefined
by
default)
useWebWorkers (boolean)
undefined
by default)Returns:
Promise
zip.Writer
constructor used) as resolved value
// 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();
zip.ZipWriter(writer [, options])
Create a ZipWriter
object
Parameters:
writer (zip.Writer)
zip.Writer
object used to write output dataoptions (Object)
zip64 (boolean)
false
by default)level (number)
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)
extendedTimestamp (boolean)
true
by default)lastAccessDate (Date)
creationDate (Date)
version (number)
undefined
by default)versionMadeBy (number)
29
by default)password (string)
undefined
by default)encryptionStrength (number)
1
for AES-128, 2
for AES-192,
3
for AES-256 (3
by default)
zipCrypto (boolean)
false
by default)
useWebWorkers (boolean)
undefined
by default)dataDescriptor (boolean)
true
by
default)
dataDescriptorSignature (boolean)
true
by
default)
signal (AbortSignal)
internalFileAttribute (number)
undefined
by default)externalFileAttribute (number)
undefined
by default)zip.ZipWriter#add(name , reader [, options])
Add a new entry into the zip
Parameters:
name (string)
reader (zip.Reader)
zip.Reader
object used to read entry data to add -
null for directory entryoptions (Object)
onprogress (Function)
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)
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)
undefined
by default)lastModDate (Date)
extendedTimestamp (boolean)
true
by default)lastAccessDate (Date)
creationDate (Date)
version (number)
undefined
by default)versionMadeBy (number)
29
by default)password (string)
undefined
by default)encryptionStrength (number)
1
for AES-128, 2
for AES-192,
3
for AES-256 (3
by default)
zipCrypto (boolean)
false
by default)
zip64 (boolean)
undefined
by default)extraField (Map)
(number)
is the type of the extra field and
the value is a UInt8Array
(undefined
by default)useWebWorkers (boolean)
undefined
by default)dataDescriptor (boolean)
true
by
default)
dataDescriptorSignature (boolean)
true
by
default)
signal (AbortSignal)
internalFileAttribute (number)
undefined
by default)externalFileAttribute (number)
undefined
by default)Returns:
Promise
Entry
object as resolved valuezip.ZipWriter#close([comment], [options])
Close the zip file
Parameters:
comment (UInt8Array)
options (Object)
onprogress (Function)
index (number)
value, a max (number)
value (undefined
by default) and the file entry
zip64 (boolean)
undefined
by default)Returns:
Promise
writer.getData()
as resolved value// 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 = blobWriter.getData();
// - 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 can be used with zip.js in favor of better performance and/or better compliance.
Pako is a handwritten JavaScript port of zlib. Its compatibility and performance is believed to be good. To use pako, configure zip.js as follows:
zip.configure({
workerScripts: {
deflate: ["library_path/z-worker-pako.js", "library_path/pako.min.js"],
inflate: ["library_path/z-worker-pako.js", "library_path/pako.min.js"]
}
});
Pako also has separate js files for deflating/inflating, you can also use them instead of
pako.min.js
:
zip.configure({
workerScripts: {
deflate: ["library_path/z-worker-pako.js", "library_path/pako_deflate.min.js"],
inflate: ["library_path/z-worker-pako.js", "library_path/pako_inflate.min.js"]
}
});
library_path/z-worker-pako.js
is the entry script for pako. This file can
be found in the /dist/
directory
const { Deflate, Inflate } =
zip.initShimAsyncCodec(
pako,
{ deflate: { raw: true }, inflate: { raw: true } },
(codec, onData) => codec.onData = onData
);
zip.configure({
useWebWorkers: false,
Deflate,
Inflate
});
Note that pako.min.js
etc. are parts of pako project, and are not provided by zip.js.
You can find them here.
fflate claims to be the fastest, smallest, and most versatile pure JavaScript compression and decompression library in existence. To use fflate, configure zip.js as follows:
zip.configure({
workerScripts: {
deflate: ["library_path/z-worker-fflate.js", "library_path/fflate.min.js"],
inflate: ["library_path/z-worker-fflate.js", "library_path/fflate.min.js"]
}
});
library_path/z-worker-fflate.js
is the entry script for fflate. This file can
be found in the /dist/
directory
const { Deflate, Inflate } =
zip.initShimAsyncCodec(
fflate,
undefined,
(codec, onData) => codec.ondata = onData
);
zip.configure({
useWebWorkers: false,
Deflate,
Inflate
});
Note that fflate.min.js
is part of fflate project, and is not provided by zip.js. You
can download it here.