JSZip API参考手册

文件地址:<script src="http://docs.asprain.cn/jszip/jszip.js"></script>

压缩版本:<script src="http://docs.asprain.cn/jszip/jszip.min.js"></script>

Contributing贡献

Download the sources下载源代码

You should create a Github account and fork the repository (you will need one to create the pull request).您应该创建一个Github帐户然后分叉存储库(您需要一个帐户来创建pull请求)。

If you just want the get the source code, you can use git and do git clone https://github.com/Stuk/jszip.git to get the sources.如果您只想获得源代码,可以使用git并运行git clone https://github.com/Stuk/jszip.git以获取来源。You can also download the latest sources here.你也可以在这里下载最新的资源。

Building the project构建项目

Code

The dependencies are handled by npm, the first step is to run npm install to get the dependencies.依赖项由npm处理,第一步是运行npm install以获取依赖项。JSZip uses Grunt to handle the build, see here to install its CLI.JSZip使用Grunt来处理构建,请参阅此处以安装其CLI。

Here are the interesting build commands :以下是有趣的构建命令:

  • grunt will generate the final js file in dist/ and the minified version.将生成dist/中的最终js文件和缩小版本。
  • npm run test-node will run the tests in nodejs.将在nodejs中运行测试。
  • npm run test-browser will the tests in some browsers using SauceLabs, see below.将在某些浏览器中使用SauceLabs进行测试,请参阅下文。
  • npm run test will run the tests in nodejs and in the browser.将在nodejs和浏览器中运行测试。
  • npm run lint will use jshint the check the source code.将使用jshint检查源代码。

Documentation文档

The documentation uses jekyll on gh-pages.文档在gh页面上使用了jekyll。To render the documentation, you need to install jekyll and then run jekyll serve --baseurl ''.要呈现文档,您需要安装jekyll,然后运行jekyll serve --baseurl ''

Testing the project测试项目

To test JSZip in nodejs, use npm run test-node.要在nodejs中测试JSZip,请使用npm run test-node

To test JSZip in a browser, you can open the file test/index.html in the browser you want to test.要在浏览器中测试JSZip,可以在要测试的浏览器中打开文件test/index.htmlDon't forget to update the dist/ files with grunt.别忘了用grunt更新dist/文件。

You can also test JSZip in a lot of browsers at once with SauceLabs.您还可以使用SauceLabs在许多浏览器中同时测试JSZip。You will need a SauceLabs account and two variables into your environment.您将需要一个SauceLabs帐户和两个变量到您的环境中。On linux, just use在linux上,只需在运行npm run test-browser命令之前使用

export SAUCE_USERNAME=your-saucelabs-username
export SAUCE_ACCESS_KEY=your-saucelabs-access-key

before running the npm run test-browser command.

Merging the changes合并更改

If you have tested bug fixes or new features, you can open a pull request on Github.如果您已经测试了bug修复或新功能,您可以在Github上打开一个pull请求

Releasing a new version发布新版本

  1. In package.json temporarily change "./lib/index" to "."
  2. Run npm test
  3. Update JSZip.version in index.js and in package.json
  4. Run grunt to generate the new dist files
    • undo the package.json change, it was just needed to replace the __VERSION__ in the header
  5. Undo step 1.
  6. Update CHANGES.md
  7. Run npm version ... where ... is major, minor, or patch
  8. Run npm publish

Upgrade Guide

From 2.x to 3.0.0

  • Deprecated objects/methods has been removed:
    • options.base64 in generate() (the base64 type is still valid)
    • options.base64, options.binary, options.dir, options.date on ZipObject (see the 2.3 upgrade section)
    • JSZip.utils
    • JSZip.prototype.crc32, JSZip.prototype.utf8encode, JSZip.prototype.utf8decode
    • JSZip.base64 (you can get the content of a file directly as a base64 string)
  • JSZip.compressions has been removed.
  • On ZipObject, the synchronous getters has been replaced by async() and nodeStream().
  • The generate() method has been replaced by generateAsync() and generateNodeStream().
  • The type option in generate() is now mandatory.
  • The "text" type has been replaced by the "string" type, a binary string is named "binarystring".
  • The load() method and the constructor with data (new JSZip(data)) have been replaced by loadAsync().
  • When adding a file, the option createFolders now defaults to true. If you don't want to create sub folders, set it to false.
  • zip.generateAsync() and zip.generateNodeStream() now depend on the current folder level.
// 2.x
zip.file("test.txt").asText();
// 3.x
zip.file("test.txt").async("string")
.then(function (content) {
    // use content
});


// 2.x
zip.generate();
// 3.x
zip.generateAsync({type:"uint8array"})
.then(function (content) {
    // use content
});

// 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

// 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;
});

async and loadAsync use (a polyfill of) promises, you can find the documentation here and a tutorial here.

It is worth noting that:

/*
 * JSZip accepts these promise as input
 */

// replace a content with JSZip v2
var content = zip.file("my_file").asText();
content = content.replace(/apples/, 'oranges');
zip.file("my_file", content);

// replace a content with JSZip v3
var contentPromise = zip.file("my_file").async("text").then(function (content) {
    return content.replace(/apples/, 'oranges');
});
zip.file("my_file", contentPromise);


/*
 * Promises are chainable
 */

// read, update, generate a zip file with JSZip v2
var zip = new JSZip(content);
zip.file("new_file", "new_content");
var blob = zip.generate({type: "blob"});
saveAs(blob, "result.zip");

// read, update, generate a zip file with JSZip v3
JSZip.loadAsync(content)
.then(function (zip) {
    zip.file("new_file", "new_content");
    // if you return the zip object, it will be available in the next "then"
    return zip;
.then(function (zip) {
    // if you return a promise of a blob, promises will "merge": the current
    // promise will wait for the other and the next "then" will get the
    // blob
    return zip.generateAsync({type: "blob"});
.then(function (blob) {
    saveAs(blob, "result.zip");
});

From 2.2.2 to 2.3.0

  • On ZipObject#options, the attributes date and dir have been deprecated and are now on ZipObject.
  • On ZipObject#options, the attributes base64 and binary have been deprecated.
  • JSZip.base64, JSZip.prototype.crc32, JSZip.prototype.utf8decode, JSZip.prototype.utf8encode and JSZip.utils have been deprecated.
// deprecated
zip.file("test.txt").options.date
zip.file("test.txt").options.dir
// new API
zip.file("test.txt").date
zip.file("test.txt").dir

From 2.0.0 to 2.1.0

  • The packaging changed : instead of loading jszip.js, jszip-load.js, jszip-inflate.js, jszip-deflate.js, just include dist/jszip.js or dist/jszip.min.js. For AMD loader users : JSZip now registers itself. You just have to put the file at the right place or configure your loader.

From 1.x to 2.x

  • JSZipBase64 has been renamed to JSZip.base64.
  • The data attribute doesn't exist anymore : use the getters asText(), asBinary(), etc
  • The compression/decompression methods now give their input type with the compressInputType and uncompressInputType attributes.

Example for the data attribute :

// before
zip.file("test.txt").data;
zip.files["test.txt"].data;
zip.file("image.png").data;
zip.files["image.png"].data;

// after
zip.file("test.txt").asText();
zip.files["test.txt"].asText();
zip.file("image.png").asBinary();
zip.files["image.png"].asBinary();

JSZip API

An instance of JSZip represents a set of files.一个JSZip的实例代表了一个文件集。You can add them, remove them, modify them.你可以添加它们、删除它们,修改它们。You can also import an existing zip file or generate one.你还可以导入一个已有的Zip文件或生成一个Zip文件。

特性

attribute name特性名称 type类型 description描述
files object the ZipObjects inside the zip with the name as key.zip里的一个ZipObject,其名称作为键。See file(name).请参阅file(name)
comment string the comment of the zip file.zip文件的注释

new JSZip() or JSZip()

Create a new JSZip instance.创建一个新的JSZip实例。

返回 : A new JSZip.一个新的JZZip实例。

始于: v1.0.0

示例

var zip = new JSZip();
// same as
var zip = JSZip();

file(name)

Get a file with the specified name.取得带有指定名称的文件。You can specify folders in the name : the folder separator is a forward slash (“/”).你可以在name中指定文件夹:文件夹分隔符是一个斜杠(“/”)。

返回 : An instance of ZipObject representing the file if any, null otherwise.如果文件存在的话,是代表该文件的一个ZipObject实例,否则为null

始于: v1.0.0

形参

name名称 type类型 description描述
name string the name of the file.文件的名称

抛出异常 : Nothing.无。

示例

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
// utf8 example
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
// 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

file(regex)

Search a file in the current folder and subfolders with a regular expression.利用一个正则表达式在当前的文件和子文件夹中搜索一个文件。 The regex is tested against the relative filename.针对相对文件名测试正则表达式。

返回 : An array of matching files (an empty array if none matched).一个匹配文件的数组(如果没有匹配到则为空数组)。Each matching file is an instance of ZipObject.每个匹配的文件是一个ZipObject的实例。

始于: v1.0.0

形参

name名称 type类型 description描述
regex RegExp the regex to use.用到的正则表达式

示例

var zip = new JSZip();
zip.file("file1.txt", "content");
zip.file("file2.txt", "content");
zip.file(/file/); // array of size 2
// example with a relative path :
var folder = zip.folder("sub");
folder
.file("file3.txt", "content")  // relative path from folder : file3.txt
.file("file4.txt", "content"); // relative path from folder : file4.txt
folder.file(/file/);  // array of size 2
folder.file(/^file/); // array of size 2, the relative paths start with file
// arrays contain objects in the form:
// {name: "file2.txt", dir: false, async : function () {...}, ...}

file(name, data [,options])

Add (or update) a file to the zip file.将文件添加或更新到Zip文件。If something goes wrong (the data is not in a supported format for example), an exception will be propagated when accessing the data.如果出了什么错误(例如数据是不受支持的格式),在访问数据时,将传播一个异常。

返回 : The current JSZip object, for chaining.当前的JSZip对象,用于连缀。

始于: v1.0.0

形参

name名称 type类型 description描述
name string the name of the file.文件的名称。You can specify folders in the name : the folder separator is a forward slash (“/”).你可以在name中指定文件夹:文件夹分隔符是一个斜杠(“/”)。
data String/ArrayBuffer/Uint8Array/
Buffer/Blob/Promise/Nodejs stream
the content of the file.文件的内容。
options object the options.选项。

Content of options :options的内容:

name名称 type类型 default默认值 description描述
base64 boolean false set to true if the data is base64 encoded.如果数据是base64编码的,则设置为trueFor example image data from a <canvas> element.例如来自<canvas>元素的图像。Plain text and HTML do not need this option.纯文本和HTML不需要此选项。More.更多更多
binary boolean false set to true if the data should be treated as raw content, false if this is a text.如果数据必须被视为生内容,则设置为true,如果它是文本,则设置为falseIf base64 is used, this defaults to true, if the data is not a string, this will be set to true.如果使用了base64,则默认值为true,如果数据不是字符串,它将被设置为trueMore.更多更多
date date the current date当前数据 the last modification date.最后的修改日期。More.更多更多
compression string null If set, specifies compression method to use for this specific file.如果设置的话,指定针对此特定文件的压缩方法。If not, the default file compression will be used, see generateAsync(options).如果没有设置,将使用默认文件压缩方法,请参阅generateAsync(options)More.更多
compressionOptions object null the options to use when compressing the file, see generateAsync(options).当压缩文件时使用的选项,请参阅generateAsync(options)More.更多
comment string null The comment for this file.针对此文件的注释。More.更多
optimizedBinaryString boolean false Set to true if (and only if) the input is a “binary string” and has already been prepared with a 0xFF mask.当且仅当输入是“二进制字符串”并已经带有0xFF前导掩码时,才设置为true。
createFolders boolean 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.如果应自动创建文件路径中的文件夹,则设置为true,否则将只存在表示文件路径的虚拟文件夹。More.更多
unixPermissions 16 bits number null The UNIX permissions of the file, if any.文件的UNIX权限(如果有)。More.更多
dosPermissions 6 bits number null The DOS permissions of the file, if any.文件的DOS权限(如果有)。More.更多
dir boolean false Set to true if this is a directory and content should be ignored.如果这是一个目录并且应该忽略内容,则设置为true。More.更多
data input

You shouldn’t update the data given to this method: it is kept as it so any update will impact the stored data.您不应该更新提供给此方法的数据:它保持原样,因此任何更新都会影响存储的数据。

About Promise since v3.0.0

You can use a Promise of content directly to simplify async content handling.你可以使用一个内容的预约以简化异步内容处理。Let’s use HTTP calls as examples:我们用一个HTTP调用作为示例:

/** with promises **/
// 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);
/** with callbacks **/
// instead of
request('url/to.file.txt', function (error, response, body) {
zip.file("file.txt", body);
});
// you can do
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);

About Blob since v3.0.0

You can use directly Blob as input, no need to use a FileReader.你可以直接使用Blob作为输入,而不需要使用FileReaderFile objects are Blobs so you can use them directly:File对象也是二进制对象,所以你可以直接使用它们:

// in a change callback of a <input type="file">
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
zip.file(f.name, f);
}

About nodejs stream since v3.0.0

A stream can’t be restarted: if it is used once, it can’t be used again (by generateAsync() or by ZipObject methods).一个流不能被重新开始:一旦它已被使用过,它就不能再次(被generateAsync()方法或ZipObject的方法)使用。In that case, the promise/stream (depending on the method called) will get an error.否则的话,promise/stream(取决于调用的方法)将得到错误。

base64 option选项
var zip = new JSZip();
zip.file("hello.txt", "aGVsbG8gd29ybGQK", {base64: true});
binary option选项
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});

If you use a library that returns a binary string for example, you should use this option.例如,如果使用返回二进制字符串的库,则应使用此选项。Otherwise, you will get a corrupted result: JSZip will try to encode this string with UTF-8 when the content doesn’t need to.否则,您将得到一个损坏的结果:当内容不需要时,JSZip将尝试用UTF-8编码这个字符串。

date option选项
zip.file("Xmas.txt", "Ho ho ho !", {
date: new Date("December 25, 2007 00:00:01")
});
compression and compressionOptions options

See also the same options on JSZip#generateAsync().请参阅JSZip#generateAsync()中的同一个选项。

These options will be used when generating a zip file.当生成一个zip文件时,将使用这些选项。They let you override entry per entry the compression / compression options to use.它们允许您为每个条目覆盖要使用的压缩/压缩选项。

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"
});
comment option选项
zip.file("a.txt", "content", {
comment: "comment of a.txt"
});
createFolders option选项
zip.file("a/b/c/d.txt", "content", {
createFolders: true // default value
});
console.log(zip.files);
// will display:
// - a/
// - a/b/
// - a/b/c/
// - a/b/c/d.txt
zip.file("a/b/c/d.txt", "content", {
createFolders: false
});
console.log(zip.files);
// will display:
// - a/b/c/d.txt
unixPermissions and dosPermissions options

Each permission will be used for matching platform option of generateAsync(): on DOS, use dosPermissions, on UNIX, use unixPermissions.每项权限将被用来匹配generateAsync()的平台选项:在DOS上,使用dosPermissions,在UNIX上,使用unixPermissions

On nodejs you can use the mode attribute of nodejs’ fs.Stats.在nodejs上,你可以使用nodejs’ fs.Statsmode特性。

When not set, a default value will be generated:如果不设置,将生成默认的值。

  • 0100664 or 040775 for UNIX0100664040775针对UNIX
  • standard file or standard directory for DOS标准文件或标准目录针对DOS

The field unixPermissions also accepts a string representing the octal value: “644”, “755”, etc.字段unixPermissions还接收一个string,它代表了八进值值“644”、“755”,等等。

zip.file("script.sh", "#!/bin/bash", {
unixPermissions: "755"
});
dir option选项

If dir is true or if a permission says it’s a folder, this entry be flagged as a folder and the content will be ignored.如果dir是true,或某项授权说它是一个文件夹,则此条目将被标记为文件夹,内容将被忽略。

See also folder(name).另请参阅folder(name)

zip.file("folder/", null, {
dir: true
});

其它示例

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

folder(name)

Create a directory if it doesn’t exist, return a new JSZip object with the new folder as root.创建一个不存在的目录,返回一个新的JSZip对象,新文件夹作为根目录。

See also the dir option of file().另请参阅file()dir选项。

返回 : A new JSZip (for chaining), with the new folder as root.一个新的JSZip(用于连缀),用新文件夹作为根。

始于: v1.0.0

形参

name名称 type类型 description描述
name string the name of the directory.目录的名称。

示例

zip.folder("images");
zip.folder("css").file("style.css", "body {background: #FF0000}");
// or specify an absolute path (using forward slashes)
zip.file("css/font.css", "body {font-family: sans-serif}")
// result : images/, css/, css/style.css, css/font.css

folder(regex)

Search a subdirectory in the current directory with a regular expression.在当前目录中利用正则表达式搜索一个子目录。The regex is tested against the relative path.针对相对路径测试正则表达式。

返回 : An array of matching folders (an empty array if none matched).匹配文件夹的数组(如果没有匹配,则为空数组)。Each matching folder is an instance of ZipObject.每个匹配的文件夹是一个ZipObject实例。

始于: v1.0.0

形参

name名称 type类型 description描述
regex RegExp the regex to use.所用的正则表达式。

示例

var zip = new JSZip();
zip.folder("home/Pierre/videos");
zip.folder("home/Pierre/photos");
zip.folder("home/Jean/videos");
zip.folder("home/Jean/photos");
zip.folder(/videos/); // array of size 2
zip.folder("home/Jean").folder(/^vid/); // array of 1

forEach(callback)

Call a callback function for each entry at this folder level.针对文件夹级别的每个条目调用一个回调函数。

返回 : Nothing.

始于: v3.0.0

形参

name名称 type类型 description描述
callback function the callback to use.所用的回调函数。

The callback has the following signature : function (relativePath, file) {...} :回调函数具有以下签名:function (relativePath, file) {...}

name名称 type类型 description描述
relativePath string the filename and its path, relative to the current folder.文件名和它的路径,相对于当前文件夹。
file ZipObject the current file.当前文件。See ZipObject.请参阅ZipObject

示例

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

filter(predicate)

Filter nested files/folders with the specified function.利用指定的函数筛选嵌套的文件、文件夹。

返回 : An array of matching ZipObject.匹配的ZipObject的数组。

始于: v1.0.0

形参

name名称 type类型 description描述
predicate function the predicate to use.要使用的谓词。

The predicate has the following signature : function (relativePath, file) {...} :谓词具有以下签名:function (relativePath, file) {...}

name名称 type类型 description描述
relativePath string the filename and its path, relative to the current folder.文件名和它的路径,相对于当前文件夹。
file ZipObject the file being tested.被测试的文件。See ZipObject.请参阅ZipObject

The predicate must return true if the file should be included, false otherwise.如果文件应该被包含的话,谓词应该返回true,否则返回false

示例

var zip = new JSZip().folder("dir");
zip.file("readme.txt", "content");
zip.filter(function (relativePath, file){
// relativePath == "readme.txt"
// file = {name:"dir/readme.txt",options:{...},async:function}
return true/false;
});

remove(name)

Delete a file or folder (recursively).递归地删除一个文件或文件夹。

返回 : The current JSZip object.当前的JSZip对象。

始于: v1.0.0

形参

name名称 type类型 description描述
name string the name of the file/folder to delete.要删除的文件、文件夹的名称。

示例

var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
zip.file("temp.txt", "nothing").remove("temp.txt");
// result : Hello.txt
zip.folder("css").file("style.css", "body {background: #FF0000}");
zip.remove("css");
//result : empty zip

generateAsync(options[, onUpdate])

Generates the complete zip file at the current folder level.在当前的文件夹级别生成一个完整的Zip文件。

返回 : A Promise of the generated zip file.生成的zip文件的Promise

An error will be propagated if the asked type is not available in the browser, see JSZip.support.如果被要求的type在浏览器中不可用,将传播一个错误,请参阅JSZip.support

始于: v3.0.0

形参

name名称 type类型 default默认值 description描述
options object   the options to generate the zip file :生成Zip文件的选项:
options.type string   The type of zip to return, see below for the other types.要返回的Zip的类型,请参阅下面以了解其它类型。Required.必不可少More.更多
options.compression string STORE (no compression) the default file compression method to use.要使用的默认文件压缩方法。More.更多
options.compressionOptions object null the options to use when compressing the file.在压缩文件时要使用的选项。More.更多
options.comment string   The comment to use for the zip file.针对zip文件要使用的注释。More.更多
options.mimeType string application/zip mime-type for the generated file.针对生成的文件的mime类型。More.更多
options.platform string DOS The platform to use when generating the zip file.当生成zip文件时要使用的平台。More.更多
options.encodeFileName function encode with UTF-8用UTF-8编码 the function to encode the file name / comment.编码文件名、注释的函数。More.更多
options.streamFiles boolean false Stream the files and create file descriptors, see below.流化文件并创建文件描述符,请看下面。More.更多
onUpdate function   The optional function called on each internal update with the metadata.使用元数据对每个内部更新调用的可选函数。More.更多
type option选项

Possible values for type :针对type可用 的值。

  • base64: the result will be a string, the binary in a base64 form.结果将是字符串,二进制将用base64形式。
  • binarystring (or string, deprecated): the result will be a string in “binary” form, using 1 byte per char (2 bytes).(或者string,建议弃用):结果将以“二进制”形式的字符串,每个字符使用一字节(或二字节)。
  • array: the result will be an Array of bytes (numbers between 0 and 255) containing the zip.结果将是一个包含zip的字节数组(0到255之间的数字)。
  • uint8array: the result will be a Uint8Array containing the zip.结果将是一个包含zip的Uint8Array。This requires a compatible browser.这需要一个兼容的浏览器。
  • arraybuffer: the result will be a ArrayBuffer containing the zip.结果将是一个包含zip的ArrayBuffer。This requires a compatible browser.这需要一个兼容的浏览器。
  • blob: the result will be a Blob containing the zip.结果将是一个包含zip的Blob。This requires a compatible browser.这需要一个兼容的浏览器。
  • nodebuffer: the result will be a nodejs Buffer containing the zip.结果将是一个包含zip的nodejs缓冲。This requires nodejs.这需要nodejs。

Note : when using type = “uint8array”, “arraybuffer” or “blob”, be sure to check if the browser supports it (you can use JSZip.support).注意:使用type="unit8array"、"arraybuffer"或"blob"时,请先确定浏览器是否支持它(你可以使用JSZip.support来测试)。

zip.generateAsync({type: "uint8array"}).then(function (u8) {
// ...
});
compression and compressionOptions options

Available compression methods are STORE (no compression) and DEFLATE.可用的compression方法是STORE(不压缩)和DEFLATE

The compressionOptions parameter depends on the compression type.compressionOptions参数取决于压缩类型。With STORE (no compression), this parameter is ignored.利用STORE(不压缩),此参数针被忽略。With DEFLATE, you can give the compression level with compressionOptions : {level:6} (or any level between 1 (best speed) and 9 (best compression)).利用DEFLATE,你可以用compressionOptions : {level:6}(或1到9之间的数字)给出压缩级别,级别1最快,级别9压缩率最高。

Note : if the entry is already compressed (coming from a compressed zip file), calling generateAsync() with a different compression level won’t update the entry.注意:如果条目已经被压缩(来自一个已压缩的zip文件),则利用不同的压缩级别调用generateAsync(),将不会更新此条目。The reason is simple : JSZip doesn’t know how compressed the content was and how to match the compression level with the implementation we use.原因很简单:JSZip不知道内容是如何压缩的,也不知道如何将压缩级别与我们所使用的实现相匹配。

zip.generateAsync({
type: "blob",
compression: "DEFLATE",
compressionOptions: {
level: 9
}
});
comment option选项

The zip format has no flag or field to give the encoding of this field and JSZip will use UTF-8.zip格式没有标记或字段来给出该字段的编码,JSZip将使用UTF-8。With non ASCII characters you might get encoding issues if the file archiver doesn’t use UTF-8 (or the given encoding) to decode the comment.对于非ASCII字符,如果文件归档器不使用UTF-8(或给定的编码)来解码注释,则可能会出现编码问题。

zip.generateAsync({
type: "blob",
comment: "The comment text for this zip file"
})
mimeType option选项

This field is used when you generate a Blob and need to change the mime type.当生成Blob并需要更改mime类型时,将使用此字段。Useful when you need to generate a file with a different extension, ie: “.ods”.当您需要生成具有不同扩展名的文件时非常有用,例如:“.ods”。

Note, this won’t change the content of the file, only the other programs may see it.请注意,这不会改变文件的人,只有其它程序可能会看到它。

//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"
});
platform option选项

Possible values for platform : DOS and UNIX.针对platform的可用的值有:DOSUNIXIt also accepts nodejs process.platform values.它还可以接受nodejsprocess.platform值。 When using DOS, the attribute dosPermissions of each file is used.当使用DOS时,将使用每个文件的dosPermissions特性。When using UNIX, the attribute unixPermissions of each file is used.当使用UNIX时,将使用每个文件的unixPermissions特性。

If you set the platform value on nodejs, be sure to use process.platform.如果在nodejs上设置平台值,请确保使用process.platformfs.stats returns a non executable mode for folders on windows, if you force the platform to UNIX the generated zip file will have a strange behavior on UNIX platforms.fs.stats针对windows上的文件夹返回一个不可执行的模式,如果你强行将平台设置为UNIX,则生成的zip文件将在UNIX平台上具有奇怪的行为。

// on nodejs
zip.file(pathname, content, {
date: stat.mtime,
unixPermissions: stat.mode
});
// ...
zip.generateAsync({
type: 'nodebuffer',
platform: process.platform
});
encodeFileName option选项

By default, JSZip uses UTF-8 to encode the file names / comments.默认情况下,JSZip使用UTF-8来编码文件名、注释。You can use this method to force an other encoding.你可以使用此方法强行设置一个其它的编码方法。Note: the encoding used is not stored in a zip file, not using UTF-8 may lead to encoding issues.注意:编码方法将不会存储在zip文件中,不使用UTF-8可能会导致编码问题。The function takes a string and returns a bytes array (Uint8Array or Array).此函数取用了一个字符串,并返回一个字节数组(Unit8ArrayArray)。

See also decodeFileName on JSZip#loadAsync().另请参阅JSZip#loadAsync()中的decodeFileName

// using iconv-lite for example
var iconv = require('iconv-lite');
zip.generateAsync({
type: 'uint8array',
encodeFileName: function (string) {
return iconv.encode(string, 'your-encoding');
}
});
streamFiles option选项

In a zip file, the size and the crc32 of the content are placed before the actual content: to write it we must process the whole file.在一个zip文件中,内容的尺寸和crc32被放在实际内容的前面:为了编写它,我们必须处理整个文件。When this option is false (the default) the processed file is held in memory.当此选项是false时(默认值),被处理的文件容纳在内存中。It takes more memory but generates a zip file which should be read by every program.它需要更多内存,但会生成一个zip文件,每个程序都应该读取该文件。When this options is true, we stream the file and use data descriptors at the end of the entry.当此选项是true时,我们流化文件,并在条目的末尾使用数据描述符。This option uses less memory but some program might not support data descriptors (and won’t accept the generated zip file).此选项使用较少的内存,但是有些程序可能不支持数据描述符(并且不接受生成的zip文件)。

zip.generateAsync({
type: 'uint8array',
streamFiles: true
});
onUpdate callback

If specified, this function will be called each time a chunk is pushed to the output stream (or internally accumulated).如果指定,则每次将块推送到输出流(或内部累积)时都将调用此函数。

The function takes a metadata object which contains information about the ongoing process.此函数取用metadata对象,它包含了关于正在进行的进程的信息。

Metadata : the metadata are:元数据是:

name名称 type类型 description描述
percent number the percent of completion (a double between 0 and 100)完成的百分比(0到100之间的双精度数)
currentFile string the name of the current file being processed, if any.当前正在被压缩的文件的名称,如果有该文件的话。

zip.generateAsync({type:"blob"}, function updateCallback(metadata) {
console.log("progression: " + metadata.percent.toFixed(2) + " %");
if(metadata.currentFile) {
console.log("current file = " + metadata.currentFile);
}
})

其它示例

zip.generateAsync({type:"blob"})
.then(function (content) {
// see FileSaver.js
saveAs(content, "hello.zip");
});
zip.generateAsync({type:"base64"})
.then(function (content) {
location.href="data:application/zip;base64,"+content;
});
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){/*...*/});
});

generateNodeStream(options[, onUpdate])

Generates the complete zip file as a nodejs stream.将完整的zip文件生成为nodejs流。

返回 : a nodejs Streams3.一个nodejs Streams3

始于: v3.0.0

形参

name名称 type类型 default默认值 description描述
options object   the options to generate the zip file, see the options of generateAsync()生成zip文件的选项,请参阅generateAsync()的选项
onUpdate function   The optional function called on each internal update with the metadata.使用元数据对每个内部更新调用的可选函数。

The type parameter has here the default value of nodebuffer.type参数此处具有nodebuffer的默认值。Only nodebuffer is currently supported.当前只支持nodebuffer

Metadata : see the metadata of generateAsync().请参阅generateAsync()的元数据。

示例

zip
.generateNodeStream({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.");
});

generateInternalStream(options)

Generates the complete zip file with the internal stream implementation.使用内部流实现生成完整的zip文件。

返回 : a StreamHelper.一个StreamHelper

始于: v3.0.0

形参

name名称 type类型 default默认值 description描述
options object   the options to generate the zip file, see the options of generateAsync()用来生成zip文件的选项,请参阅generateAsync()的选项

Metadata : see the metadata of generateAsync().请参阅generateAsync()的元数据

示例

zip.generateInternalStream({type:"blob"}).accumulate(function callback(err, content) {
if (err) {
// handle error
}
// see FileSaver.js
saveAs(content, "hello.zip");
}, function updateCallback(metadata) {
// print progression with metadata.percent and metadata.currentFile
});

loadAsync(data [, options])

Read an existing zip and merge the data in the current JSZip object at the current folder level.读取一个已有的zip并把数据合并到当前的JSZip对象中的当前文件夹级别。This technique has some limitations, see here.此技术有一些限制,请参阅此处If the JSZip object already contains entries, new entries will be merged.如果JSZIP已经包含了条目,新条目将合并入。If two have the same name, the loaded one will replace the other.如果有两个文件具有相同的名称,已加载的将替换另一个。

返回 : A Promise with the updated zip object.一个带有已更新的zip对象的PromiseThe promise can fail if the loaded data is not valid zip data or if it uses unsupported features (multi volume, password protected, etc).如果加载的数据不是有效的zip数据,或者使用不受支持的功能(多卷、密码保护等),则promise可能会失败。

始于: v3.0.0

形参

name名称 type类型 description描述
data String/Array of bytes字节的数组/ArrayBuffer/
Uint8Array/Buffer/Blob/Promise
the zip filezip文件
options object the options to load the zip file加载zip文件的选项。

Content of options :options的内容:

name名称 type类型 default默认值 description描述
options.base64 boolean false set to true if the data is base64 encoded, false for binary.如果数据是base64编码的,则设置为true,如果数据是二进制,则设置为falseMore.更多
options.checkCRC32 boolean false set to true if the read data should be checked against its CRC32.如果读取的数据将检查它的CRC32,则设置为trueMore.更多
options.optimizedBinaryString boolean false set to true if (and only if) the input is a string and has already been prepared with a 0xFF mask.当且仅当输入是字符串,并已经带有0xFF前导掩码时,才设置为true
options.createFolders boolean false set to true to create folders in the file path automatically.设置为true时在文件路径中自动创建文件夹。Leaving it false will result in only virtual folders (i.e. folders that merely represent part of the file path) being created.如果设置为false,则只会创建虚拟文件夹(即仅代表文件路径一部分的文件夹)。More.更多
options.decodeFileName function decode from UTF-8从UTF-8解码 the function to decode the file name / comment.用来解码文件名、注释的函数。More.更多

You shouldn’t update the data given to this method : it is kept as it so any update will impact the stored data.您不应该更新提供给此方法的数据:它保持原样,因此任何更新都会影响存储的数据。

Zip features supported by this method :被此方法所支持的Zip功能:

  • Compression (DEFLATE supported)压缩(支持DEFLATE
  • zip with data descriptor带有数据描述符的zip
  • ZIP64
  • UTF8 in file name, UTF8 in file content文件名中的UTF-8、文件内容中的UTF-8

Zip features not (yet) supported :尚不支持的Zip功能:

  • password protected zip密码保护的zip
  • multi-volume zip多卷的zip
base64 option选项
var zip = new JSZip();
zip.loadAsync("UEsDBAoDAAAAAJxs8T...AAAAAA==", {base64: true});
checkCRC32 option选项

The checkCRC32 option will load every files, compute the CRC32 value and compare it against the saved value.checkCRC32选项将加载每个文件,计算CRC32值并针对已保存的值比较它。With larger zip files, this option can have a significant performance cost.对于较大的zip文件,此选项可以带来明显的性能损失。

// here, "bin" is a corrupted zip file
zip.loadAsync(bin)
.then(function (zip) {
// will be called, even if content is corrupted
}, function (e) {
// won't be called
});
zip.loadAsync(bin, {
checkCRC32: true
})
.then(function (zip) {
// won't be called
}, function (e) {
// Error: Corrupted zip : CRC32 mismatch
});
createFolders option选项
// 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
});
decodeFileName option选项

A zip file has a flag to say if the filename and comment are encoded with UTF-8.一个zip文件有一个标志,说明文件名和注释是否用UTF-8编码。If it’s not set, JSZip has no way to know the encoding used.如果没有设置,JSZip就无法知道所使用的编码。It usually is the default encoding of the operating system.它通常是操作系统的默认编码。Some extra fields can give the unicode version of the filename/comment too (in that case, we use it).一些额外的字段也可以给出unicode版本的文件名/注释(在这种情况下,我们使用它)。

If we can’t find an UTF-8 encoded filename/comment, we use the decodeFileName function (which is by default an UTF-8 decode).如果我们无法找到一个UTF-8编码的文件名/注释,将使用decodeFileName函数(它默认是utf-8解码)。

The function takes the bytes array (Uint8Array or Array) and returns the decoded string.函数接受字节数组(Uint8Array或array)并返回解码后的字符串。

// here, "bin" is a russian zip file, using the cp866 encoding for file names
// by default, using UTF-8 leads to wrong file names:
zip.loadAsync(bin)
.then(function (zip) {
console.log(zip.files);
// '����� �����/': ...
// '����� �����/����� ⥪�⮢�� ���㬥��.txt': ...
});
// using the correct encoding solve the issue:
var iconv = require('iconv-lite');
zip.loadAsync(bin, {
decodeFileName: function (bytes) {
return iconv.decode(bytes, 'cp866');
}
})
.then(function (zip) {
console.log(zip.files);
// 'Новая папка/': ...
// 'Новая папка/Новый текстовый документ.txt': ...
});

其它示例

var zip = new JSZip();
zip.loadAsync(zipDataFromXHR);
require("fs").readFile("hello.zip", function (err, data) {
if (err) throw err;
var zip = new JSZip();
zip.loadAsync(data);
}

Using sub folders :使用子文件夹:

// here, "bin" is zip file containing:
// file1.txt
// folder1/file2.txt
var zip = new JSZip();
zip.folder("subfolder").loadAsync(bin)
.then(function (zip) {
// "zip" is still in the "subfolder" folder
console.log(zip.files);
// subfolder/file1.txt
// subfolder/folder1/file2.txt
});

Using loadAsync multiple times:使用loadAsync多次:

// here, "bin1" is zip file containing:
// file1.txt
// file2.txt
// and "bin2" is zip file containing:
// file2.txt
// file3.txt
var zip = new JSZip();
zip.loadAsync(bin1)
.then(function (zip) {
return zip.loadAsync(bin2);
}).then(function (zip) {
console.log(zip.files);
// file1.txt, from bin1
// file2.txt, from bin2
// file3.txt, from bin2
});

JSZip.loadAsync(data [, options])

This is a shortcut for这是以下内容的简写:

var zip = new JSZip();
zip.loadAsync(data, options);

Please see the documentation of loadAsync.请参阅loadAsync的文档。

Examples示例

dataAsPromise
.then(JSZip.loadAsync)
.then(function(zip) {...})

same as:等同于

JSZip.loadAsync(dataAsPromise)
.then(function(zip) {...})

JSZip.support

If the browser supports them, JSZip can take advantage of some “new” features : ArrayBuffer, Blob, Uint8Array.如果浏览器支持它们,JSZip可以利用一些“新”特性:ArrayBuffer、Blob、Uint8Array。To know if JSZip can use them, you can check the JSZip.support object.要想知道JSZip是否可以使用它们,可以检查JSZip.support对象。It contains the following boolean properties :它包含以下的布尔属性:

  • arraybuffer : true if JSZip can read and generate ArrayBuffer, false otherwise.如果JSZip可以读取并生成ArrayBuffer,则为true,否则为false。
  • uint8array : true if JSZip can read and generate Uint8Array, false otherwise.如果JSZip可以读取并生成Uint8Array,则为true,否则为false。
  • blob : true if JSZip can generate Blob, false otherwise.如果JSZip可以生成Blob,则为true,否则为false。
  • nodebuffer : true if JSZip can read and generate nodejs Buffer, false otherwise.如果JSZip可以读取并生成nodejs缓冲,则为true,否则为false。
  • nodestream : true if JSZip can read and generate nodejs stream, false otherwise.如果JSZip可以读取并生成nodejs流,则为true,否则为false。

JSZip.external

JSZip uses objects that may not exist on every platform, in which case it uses a shim.JSZip使用的对象可能并不存在于每个平台上,在这种情况下,它使用一个填充程序。Accessing or replacing these objects can sometimes be useful.访问或替换这些对象有时会很有用。JSZip.external contains the following properties :JSZip.external包含以下属性:

  • Promise : the Promise implementation used.使用了Promise实现程序。

The global object is preferred when available.当全局对象可用时,优先使用全局对象。

Example示例

// use bluebird instead
JSZip.external.Promise = Bluebird;
// use the native Promise object:
JSZip.external.Promise = Promise;

JSZip.version

The version of JSZip as a string.JSZip的版本的字符串形式。

始于: v3.1.0

示例

JSZip.version == "3.1.0";

ZipObject API

This represents an entry in the zip file.这表示zip文件中的一个条目。If the entry comes from an existing archive previously loaded, the content will be automatically decompressed/converted first.如果条目来自先前加载的现有存档,则内容将首先自动解压缩/转换。

特性

attribute name特性名称 type类型 description描述
name string the absolute path of the file文件的绝对路径
dir boolean true if this is a directory如果它是目录,则为true
date date the last modification date最后修改的日期
comment string the comment for this file文件的注释
unixPermissions 16 bits number The UNIX permissions of the file, if any.文件的UNIX权限(如果有)。
dosPermissions 6 bits number The DOS permissions of the file, if any.文件的DOS权限(如果有)。
options object the options of the file.文件的选项。The available options are :可用的选项是:
options.compression compression see请参阅file(name, data [,options])

Example:示例:

{ name: 'docs/',
dir: true,
date: 2016-12-25T08:09:27.153Z,
comment: null,
unixPermissions: 16877,
dosPermissions: null,
options: {
compression: 'STORE',
compressionOptions: null
}
}
{ name: 'docs/list.txt',
dir: false,
date: 2016-12-25T08:09:27.152Z,
comment: null,
unixPermissions: 33206,
dosPermissions: null,
options: {
compression: 'DEFLATE',
compressionOptions: null
}
}

async(type[, onUpdate])

Return a Promise of the content in the asked type.返回所要求类型的内容的Promise

返回 : A Promise of the content.内容的Promise

始于: v3.0.0

形参

name名称 type类型 description描述
type String the type of the result.结果的类型。More.更多
onUpdate Function an optional function called on each internal update with the metadata.使用元数据对每个内部更新调用的可选函数。More.更多
type option选项

Possible values for type :针对type的可用值:

  • base64 : the result will be a string, the binary in a base64 form.结果将是一个字符串,即base64格式的二进制文件。
  • text (or string): the result will be an unicode string.
  • binarystring: the result will be a string in “binary” form, using 1 byte per char (2 bytes).结果是“二进制”形式的字符串,每个字符使用1字节(2字节)。
  • array: the result will be an Array of bytes (numbers between 0 and 255).结果将是字节数组(数字界于0到255之间)。
  • uint8array : the result will be a Uint8Array.结果将是Unit8Array。This requires a compatible browser.这需要一个兼容的浏览器。
  • arraybuffer : the result will be a ArrayBuffer.结果将是ArrayBuffer。This requires a compatible browser.这需要一个兼容的浏览器。
  • blob : the result will be a Blob.结果将是Blob。This requires a compatible browser.这需要一个兼容的浏览器。
  • nodebuffer : the result will be a nodejs Buffer.结果将是nodejs缓冲。This requires nodejs.这需要nodejs。

Note : when using type = “uint8array”, “arraybuffer” or “blob”, be sure to check if the browser supports it (you can use JSZip.support).注意:使用type="unit8array"、"arraybuffer"或"blob"时,请先确定浏览器是否支持它(你可以使用JSZip.support来测试)。

zip.file("image.png").async("uint8array").then(function (u8) {
// ...
});
onUpdate callback

If specified, this function will be called each time a chunk is pushed to the output stream (or internally accumulated).如果指定,则每次将块推送到输出流(或内部累积)时都将调用此函数。

The function takes a metadata object which contains information about the ongoing process.函数取用一个metadata对象,它包含了关于正在进行的进程的信息。

Metadata : the metadata are :元数据是:

name名称 type类型 description描述
percent number the percent of completion (a double between 0 and 100)完成的百分比(0到100之间的双精度数)
zip.file("image.png").async("uint8array", function updateCallback(metadata) {
console.log("progression: " + metadata.percent.toFixed(2) + " %");
}).then(function (u8) {
// ...
})

其它示例

zip
.file("my_text.txt")
.async("string")
.then(function success(content) {
// use the content
}, function error(e) {
// handle the error
});

nodeStream(type[, onUpdate])

Return a nodejs Streams3 of the content in the asked type.返回所要求类型的内容的nodejs Streams3

返回 : a nodejs Streams3.一个nodejs Streams3

形参

name名称 type类型 default默认值 description描述
type String nodebuffer only nodebuffer is currently supported.当前只支持nodebuffer
onUpdate Function   an optional function called on each internal update with the metadata.一个可选的函数,在内部调用以更新元数据。

Metadata : see the metadata of async().请参阅async()的元数据

示例

zip
.file("my_text.txt")
.nodeStream()
.pipe(fs.createWriteStream('/tmp/my_text.txt'))
.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("text file written.");
});

internalStream(type)

Return a StreamHelper of the content in the asked type.返回所要求类型中内容的StreamHelper

返回 : a StreamHelper of the content in the asked type.所要求类型的内容的StreamHelper

形参

name名称 type类型 description描述
type String the type of the result: string, binarystring, uint8array, arraybuffer, nodebuffer.结果的类型:stringbinarystringuint8arrayarraybuffernodebuffer

示例

zip
.file("my_text.txt")
.internalStream("string")
.on("data", function (data) {...})
.on("error", function (e) {...})
.on("end", function () {...});

StreamHelper API

A StreamHelper can be viewed as a pausable stream with some helper methods.StreamHelper可以通过一些助手方法被视为可暂停的流。It is not a full featured stream like in nodejs (and can’t directly used as one) but the exposed methods should be enough to write the glue code with other async libraries :它不像nodejs那样是一个功能齐全的流(不能作为一个流使用),但是公开的方法应该足够编写与其他异步库的粘合代码:on('data', function), on('end', function) and on('error', function).on('data', function)on('end', function)on('error', function)

It starts paused, be sure to resume() it when ready.它开始暂停,确保在它就绪时resume()它。

If you are looking for an asynchronous helper without writing glue code, take a look at accumulate(function).如果您正在寻找一个不需要编写粘合代码的异步助手,请看一下accumulate(function)


accumulate([updateCallback])

Read the whole stream and call a callback with the complete content.读取整个流并调用包含完整内容的回调。

返回 : A Promise of the full content.完整的内容的Promise

始于: v3.0.0

形参

name名称 type类型 description描述
updateCallback function the function called every time the stream updates. This function is optional.每次流更新时调用的函数。此功能是可选的。

The update callback function takes 1 parameter: the metadata (see the on method).更新回调函数取用一个参数:元数据(请参阅on方法)。

示例

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)
});

accumulate([updateCallback])

Read the whole stream and call a callback with the complete content.读取整个流并调用包含完整内容的回调。

返回 : A Promise of the full content.完整内容的Promise

始于: v3.0.0

形参

name名称 type类型 description描述
updateCallback function the function called every time the stream updates.每次流更新时调用的函数。This function is optional.此函数是可选的。

The update callback function takes 1 parameter: the metadata (see the on method).更新回调函数取用一个参数:元数据(请参阅on方法)。

示例

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)
});

resume()

Resume the stream if the stream is paused.如果流暂停的话重启流。Once resumed, the stream starts sending data events again.一旦重启,流将再次开始发送data事件了。

返回 : The current StreamHelper object, for chaining.当前的StreamHelper对象,用于连缀。

始于: v3.0.0

示例

zip
.generateInternalStream({type:"uint8array"})
.on('data', function() {...})
.resume();

pause()

Pause the stream if the stream is running.如果流正在运行的话,暂停流。Once paused, the stream stops sending data events.一旦暂停,流将停止发送data事件了。

返回 : The current StreamHelper object, for chaining.当前的StreamHelper对象,用于连缀。

示例

zip
.generateInternalStream({type:"uint8array"})
.on('data', function(chunk) {
// if we push the chunk to an other service which is overloaded, we can
// pause the stream as backpressure.
this.pause();
}).resume(); // start the stream the first time

How To Read Zip

This page explains how to read an existing zip file or add a existing file into the zip file.本页介绍如何读取现有zip文件或将现有文件添加到zip文件中。

In the browser在浏览器中

AJAX requestAJAX请求

Getting binary data with an ajax request is hard (mainly because of IE <= 9). 使用ajax请求获取二进制数据很困难(主要是因为IE<=9)。The easy way is to use JSZipUtils.getBinaryContent. 简单的方法是使用JSZipUtils.getBinaryContentWith JSZipUtils.getBinaryContent, you can do the following (see the documentation for more examples) :使用JSZipUtils.getBinaryContent,您可以执行以下操作(有关更多示例,请参阅文档):

JSZipUtils.getBinaryContent('path/to/content.zip', function(err, data) {
    if(err) {
        throw err; // or handle err
    }

    JSZip.loadAsync(data).then(function () {
        // ...
    });
});

// or, with promises:

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(...)

If you need to adapt an existing solution to what getBinaryContent does, here are the details. 如果需要使现有解决方案适应getBinaryContent的功能,请参阅以下详细信息。When doing a XHR request (level 1, without setting the responseType) the browser will try to interpret the response as a string and decode it from its charset. 当执行XHR请求(级别1,不设置responseType)时,浏览器将尝试将响应解释为字符串并从其字符集对其进行解码。To avoid this on Firefox/Chrome/Opera, you need to set mime type : xhr.overrideMimeType("text/plain; charset=x-user-defined");. 为了避免在Firefox/Chrome/Opera上出现这种情况,您需要设置mime类型:xhr.overrideMimeType("text/plain; charset=x-user-defined");On IE <= 9, this is harder. 在IE<=9中这更难。The overrideMimeType trick doesn't work so we need to use vbscript and non standard attributes. overrideMimeType技巧不起作用,因此我们需要使用vbscript和非标准属性。On IE > 9, overrideMimeType doesn't work but xhr2 does.在IE>9上,overrideMemetype不起作用,但xhr2起作用。

With xhr 2, you can just set the responseType attribute : xhr.responseType = "arraybuffer";. 使用xhr 2,您只需设置responseType属性:xhr.responseType = "arraybuffer";With this, the browser will return an ArrayBuffer.这样,浏览器将返回一个ArrayBuffer

Local files本地文件

If the browser supports the FileReader API, you can use it to read a zip file. 如果浏览器支持FileReader API,则可以使用它读取zip文件。JSZip can read ArrayBuffer, so you can use FileReader.readAsArrayBuffer(Blob), see this example.JSZip可以读取ArrayBuffer,因此您可以使用FileReader.readAsArrayBuffer(Blob),请参阅此示例

In nodejs在nodejs中

JSZip can read Buffers so you can do the following :JSZip可以读取缓冲区,因此您可以执行以下操作:

Local file本地文件

"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) {
        // ...
    });
});
// or
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(...)


// 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);
});
// or
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);


// read a file as a stream and add it to a zip
var stream = fs.createReadStream("picture.png");
zip.file("picture.png", stream);

Remote file远程文件

There are a lot of nodejs libraries doing http requests, from the built-in http to the npm packages. 有很多nodejs库执行http请求,从内置httpnpm包Here are two examples, one with the default http API, the other with request (but you're free to use your favorite library !). 这里有两个示例,一个使用默认的http API,另一个使用request(但您可以自由使用自己喜欢的库!)。If possible, download the file as a Buffer (you will get better performances). 如果可能,请以Buffer的形式下载文件(您将获得更好的性能)。If it's not possible, you can fallback to a binary string (the option is likely to be encoding : "binary").如果不可能,您可以回退到二进制字符串(该选项可能是encoding : "binary")。

With http :
"use strict";

var http = require("http");
var url = require("url");
var JSZip = require("jszip");

var req = http.get(url.parse("http://localhost/.../file.zip"), function (res) {
  if (res.statusCode !== 200) {
    console.log(res.statusCode);
    // handle error
    return;
  }
  var data = [], dataLen = 0;

  // don't set the encoding, it will break everything !
  // or, if you must, set it to null. In that case the chunk will be a string.

  res.on("data", function (chunk) {
    data.push(chunk);
    dataLen += chunk.length;
  });

  res.on("end", function () {
    var buf = Buffer.concat(data);

    // here we go !
    JSZip.loadAsync(buf).then(function (zip) {
      return zip.file("content.txt").async("string");
    }).then(function (text) {
      console.log(text);
    });
  });
});

req.on("error", function(err){
  // handle error
});
With request :
"use strict";

var request = require('request');
var JSZip = require("jszip");

request({
  method : "GET",
  url : "http://localhost/.../file.zip",
  encoding: null // <- this one is important !
}, function (error, response, body) {
  if(error ||  response.statusCode !== 200) {
    // handle error
    return;
  }
  JSZip.loadAsync(body).then(function (zip) {
    return zip.file("content.txt").async("string");
  }).then(function (text) {
    console.log(text);
  });
});

How To Write Zip

In the browser在浏览器中

With only javascript, this part won't work in old browsers, including IE < 10. 仅使用javascript,这一部分将无法在旧浏览器中工作,包括IE<10。For those browsers, you can use a flash polyfill, see below.对于这些浏览器,您可以使用flash polyfill,请参阅下文。

You can also see this example.你还可以查看此示例

Blob URL / FileSaver

With recent browsers, the easiest way is to use saveAs or a polyfill, see FileSaver.js :对于最新的浏览器,最简单的方法是使用saveAs或polyfill,请参阅FileSaver.js

zip.generateAsync({type:"blob"})
.then(function (blob) {
    saveAs(blob, "hello.zip");
});

Under the hood, the polyfill uses the native saveAs from the FileSaver API (on Chrome and IE10+) or use a Blob URL (on Firefox).在引擎盖下,polyfill使用FileSaver API(在Chrome和IE10+上)中的原生saveAs,或者使用Blob URL(在Firefox上)。

Data URI

For older browsers that support data URI, you can also do the following :对于支持数据URI的旧浏览器,您还可以执行以下操作:

zip.generateAsync({type:"base64"}).then(function (base64) {
    location.href="data:application/zip;base64," + base64;
});

The biggest issue here is that the filenames are very awkward, Firefox generates filenames such as a5sZQRsx.zip.part (see bugs 367231 and 532230, and Safari isn't much better with just Unknown.这里最大的问题是文件名非常笨拙,Firefox生成的文件名如a5sZQRsx.zip.part(请参见bug 367231532230),而Safari使用Unknown也没什么好处。

Browser support and resulting filename :浏览器支持和生成的文件名:

Opera Firefox Safari Chrome Internet Explorer
"default.zip" random alphanumeric with ".part" extension扩展名为“.part”的随机字母数字 "Unknown" (no extension)“未知”(无扩展名) "download.zip" on OSX and Linux, just "download" on WindowsOSX和Linux上的“download.zip”,Windows上的“download”即可 No

Downloadify

Downloadify uses a small Flash SWF to download files to a user's computer with a filename that you can choose. 使用小型Flash SWF将文件下载到用户的计算机,文件名可供选择。Doug Neiner has added the dataType option to allow you to pass a zip for downloading. Doug Neiner添加了dataType选项,允许您传递zip进行下载。Follow the Downloadify demo with the following changes:按照Downloadify演示进行以下更改:

zip = new JSZip();
zip.file("Hello.", "hello.txt");

zip.generateAsync({type:"base64"}).then(function (base64) {
    Downloadify.create('downloadify',{
    ...
    data: function(){
        return base64;
    },
    ...
    dataType: 'base64'
    });
});

Deprecated google gears弃用的Google Gears

Franz Buchinger has written a brilliant tutorial on using JSZip with Google Gears (part 2). Franz Buchinger写了一篇关于将JSZip与Google Gears结合使用的精彩教程(第2部分)。If you want to let your Gears users download several files at once I really recommend having a look at some of his examples.如果你想让Gears用户一次下载几个文件,我真的建议你看看他的一些例子

In nodejs

JSZip can generate Buffers so you can do the following :JSZip可以生成缓冲区,因此您可以执行以下操作:

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.");
});

Limitations局限性

Not supported features不支持的功能

Not all features of zip files are supported.并非所有zip文件的功能都受支持。Classic zip files will work but encrypted zip, multi-volume, etc are not supported and the loadAsync() method will return a failed promise.经典zip文件可以工作,但不支持加密zip、多卷等,loadAsync()方法将返回失败的承诺。

ZIP64 and 32bit integersZIP64和32位整数

ZIP64 files can be loaded, but only if the zip file is not "too big". ZIP64文件可以加载,但前提是zip文件不是“太大”。ZIP64 uses 64bits integers but JavaScript represents all numbers as 64-bit double precision IEEE 754 floating point numbers (see section 8.5). ZIP64使用64位整数,但JavaScript将所有数字表示为64位双精度IEEE 754浮点数(参见第8.5节)。So, we have 53bits for integers and bitwise operations treat everything as 32bits. 因此,我们有53位的整数,按位运算将所有内容都视为32位So if all the 64bits integers can fit into 32 bits integers, everything will be fine. 因此,如果所有64位整数都可以放入32位整数,那么一切都会很好。If it's not the case, you will have other problems anyway (see next limitation).如果不是这样的话,您无论如何都会遇到其他问题(请参阅下一个局限性)。

Performance issues性能问题

An other limitation comes from the browser (and the machine running the browser). 另一个限制来自浏览器(以及运行浏览器的机器)。A compressed zip file of 10MB is easily opened by firefox / chrome / opera / IE10+ but will crash older IE. firefox/chrome/opera/IE10+可以轻松打开10MB的压缩zip文件,但会使旧版IE崩溃。Also keep in mind that strings in javascript are encoded in UTF-16 : a 10MB ascii text file will take 20MB of memory.还要记住,javascript中的字符串是用UTF-16编码的:一个10MB的ascii文本文件将占用20MB的内存。

The async method and the generateAsync method hold the full result in memory but doesn't freeze the browser. async方法generateAsync方法在内存中保存完整的结果,但不会冻结浏览器。If the result is too big, and if you can't use the nodeStream method or the generateNodeStream method you need to use the underlying StreamHelper to handle the result chunk by chunk and pause()/resume() to handle the backpressure.如果结果太大,并且无法使用nodeStream方法generateNodeStream方法,则需要使用底层StreamHelper逐块处理结果,并使用pause()/resume()处理背压。

If you're having performance issues, please consider the following :如果你有绩效问题,请考虑以下事项:

  • Don't use IE <= 9. 不要使用IE<=9Everything is better with typed arrays.使用类型化数组一切都会更好。
  • Use typed arrays (Uint8Array, ArrayBuffer, etc) if possible :如果可能,请使用类型化数组(Uint8ArrayArrayBuffer等):
    • If you generate a zip file, you should use type:"uint8array" (or blob, arraybuffer, nodebuffer).如果生成zip文件,则应使用type:"uint8array"(或"blob""arraybuffer""nodebuffer")。
    • If you load the file from an ajax call, ask your XHR an ArrayBuffer. 如果从ajax调用加载文件,请向XHR请求ArrayBuffer。Loading a string is asking for troubles.加载字符串会带来麻烦。

Note about compression : When reading a file, JSZip will store the content without decompressing it. 关于压缩的注意事项:当读取文件时,JSZip将存储内容而不解压缩它。When generating a compressed file, JSZip will reuse if possible the compressed content :生成压缩文件时,JSZip将尽可能重用压缩内容:

  • If you read a zip file compressed with DEFLATE and call generate with the DEFLATE compression, JSZip won't call the compression algorithms (same with STORE everywhere.)如果读取使用DEFLATE压缩的zip文件并使用DEFLATE压缩调用generate,JSZip将不会调用压缩算法(与STORE-everywhere相同)
  • If you read a zip file compressed with DEFLATE and call generate with the STORE compression, JSZip will have to decompress everything.如果您读取一个使用DEFLATE压缩的zip文件,并使用STORE压缩调用generate,那么JSZip将不得不对所有内容进行解压缩。

On IE <=9, typed arrays are not supported and the compression algorithm will fallback on arrays. 关于IE<=9,不支持类型化数组,压缩算法将回退到数组上。In that case, JSZip needs to convert the binary string into an array, DEFLATE it and convert the result into a binary string. 在这种情况下,JSZip需要将二进制字符串转换为数组,将其解压缩并将结果转换为二进制字符串。You don't want that to happen.你不希望发生这种事。

The output zip will differ from the input zip输出zip将不同于输入zip

Reading and generating a zip file won't give you back the same file. 读取和生成zip文件不会返回相同的文件。Some data are discarded (file metadata) and other are added (subfolders).一些数据被丢弃(文件元数据),另一些数据被添加(子文件夹)。

Encodings support编码支持

JSZip only supports UTF-8 natively. JSZip只原生地支持UTF-8。A zip file doesn't contain the name of the encoding used, you need to know it before doing anything.zip文件不包含所用编码的名称,您需要在执行任何操作之前了解它。

File name文件名

If the name of a file inside the zip is encoded with UTF-8 then JSZip can detect it (Language encoding flag, Unicode Path Extra Field). 如果zip中的文件名是用UTF-8编码的,那么JSZip可以检测到它(语言编码标志,Unicode路径额外字段)。If not, JSZip can't detect the encoding used and will generate Mojibake. 否则,JSZip无法检测所使用的编码,并将生成Mojibakes。You can use the encodeFileName option and the decodeFileName option to encode/decode using a custom encoding.您可以使用encodeFileName选项和decodeFileName选项使用自定义编码进行编码/解码。

File content文件内容

The async("string") method uses UTF-8 to decode the content. async("string")方法使用UTF-8对内容进行解码。If you have a text in a different encoding, you can get the bytes array with async("uint8array") and decode it with a lib (iconv, iconv-lite, etc) on your side. 如果您有一个不同编码的文本,您可以使用async("uint8array")获取字节数组,并使用您这边的lib(iconv、iconv-lite等)对其进行解码。To save a text using a non-UTF-8 encoding, do the same : encode it into a Uint8Array before adding it to JSZip.要使用非UTF-8编码保存文本,请执行相同的操作:在将文本添加到JSZip之前将其编码到Uint8Array中。


Examples示例

An instance of JSZip represents a set of files. JSZip的一个实例表示一组文件。You can add them, remove them, modify them. 您可以添加、删除、修改它们。You can also import an existing zip file or generate one.您还可以导入或生成现有的zip文件。

Getting the object获取对象

In a browser在浏览器中

For a browser, there are two interesting files : dist/jszip.js and dist/jszip.min.js (include just one).对于浏览器,有两个有趣的文件:dist/jszip.jsdist/jszip.min.js(只包括一个)。

If you use an AMD loader (RequireJS for example) JSZip will register itself :you just have to put the js file at the right place, or configure the loader (see here for RequireJS).如果您使用AMD加载程序(例如RequireJS),JSZip将自动注册:您只需将js文件放在正确的位置,或者配置加载程序(请参阅此处了解RequireJS)。

Without any loader, JSZip will declare in the global scope a variable named JSZip.如果没有任何加载程序,JSZip将在全局范围内声明一个名为JSZip的变量。

In nodejs

In nodejs, you can require it :在nodejs中,您可以require它:

var JSZip = require("jszip");

Basic manipulations基本操作

The first step is to create an instance of JSZip :第一步是创建JSZip的实例:

var zip = new JSZip();

On this instance, we can add (and update) files and folders with .file(name, content) and .folder(name). 在这个实例中,我们可以使用.file(name, content).folder(name)添加(和更新)文件和文件夹。They return the current JSZip instance so you can chain the calls.它们返回当前JSZip实例,以便您可以链接调用。

// create a file
zip.file("hello.txt", "Hello[p my)6cxsw2q");
// oops, cat on keyboard. Fixing !
zip.file("hello.txt", "Hello World\n");

// create a file and a folder
zip.file("nested/hello.txt", "Hello World\n");
// same as
zip.folder("nested").file("hello.txt", "Hello World\n");

With .folder(name), the returned object has a different root : if you add files on this object, you will put them in the created subfolder. 使用.folder(name),返回的对象具有不同的根:如果在此对象上添加文件,则会将其放入已创建的子文件夹中。This is just a view, the added files will also be in the "root" object.这只是一个视图,添加的文件也将位于“根”对象中。

var photoZip = zip.folder("photos");
// this call will create photos/README
photoZip.file("README", "a folder with photos");

You can access the file content with .file(name) and its getters :您可以使用.file(name)及其 getter访问文件内容:

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) :您还可以使用.remove(name)来删除文件或文件夹:

zip.remove("photos/README");
zip.remove("photos");
// same as
zip.remove("photos"); // by removing the folder, you also remove its content.

Generate a zip file生成一个zip文件

With .generateAsync(options) or .generateNodeStream(options) you can generate a zip file (not a real file but its representation in memory). 使用.generateAsync(options).generateNodeStream(options),您可以生成一个zip文件(不是一个真实的文件,而是它在内存中的表示形式)。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. 使用.loadAsync(data)可以加载zip文件。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"
});

FAQ

"Corrupted zip or bug: unexpected signature"“损坏的zip或错误:意外签名”

If you are sure that the zip file is correct, that error often comes from a corrupted content. 如果您确信zip文件是正确的,则该错误通常来自损坏的内容。An ajax request, if not prepared correctly, will try to decode the binary content as a text and corrupt it. ajax请求如果准备不正确,将尝试将二进制内容解码为文本并损坏它。See this page.请参阅此处

My browser crashes / becomes unresponsive / never finish the execution我的浏览器崩溃/无响应/从未完成执行

That happens if you try to handle to much data with the synchronous API. 如果您尝试使用同步API处理大量数据,就会出现这种情况。If possible, try the asynchronous API, see this page for more information.如果可能,请尝试异步API,有关更多信息,请参阅此处

Can't read the data of [...]. Is it in a supported JavaScript type ?无法读取[…]的数据。它是支持的JavaScript类型吗?

Or the old message:或者旧的信息:

The data of [...] is in an unsupported format[...]的数据格式不受支持

The method file(name, data [,options]) accepts string and binary inputs for data.file(name, data [,options])接受数据的字符串和二进制输入。

If you use an unsupported type, an object for example, you will get this error:如果使用不受支持的类型,例如对象,则会出现以下错误:

// WRONG
var data = {
    content: new ArrayBuffer(...)
};
zip.file("my.data", data); // won't work, data is an object

// CORRECT
var data = new ArrayBuffer(...);
zip.file("my.data", data); // will work, JSZip accepts ArrayBuffer

My mac generates a .cpgz file when I try to extract the zip file当我试图解压缩zip文件时,我的mac会生成一个.cpgz文件

MacOS Finder has a lot of bug related to zip files (the unzip command line tool is fine). MacOS Finder有很多与zip文件相关的bug(unzip命令行工具很好)。When something goes wrong, Finder will generate this cpgz file instead of showing an error.当出现错误时,Finder将生成这个cpgz文件,而不是显示错误。

To get a correct result, try to enable compression in generateAsync:要获得正确的结果,请尝试在generateAsync中启用压缩:

zip.generateAsync({
    type:"...",
    compression: "DEFLATE" // <-- here
});

Using platform: "UNIX" may help too.使用platform: "UNIX"可能也有帮助。