Skip to content
Browse files

issue #7 : modify the API

  • Loading branch information...
1 parent f02df57 commit 773196fcae53d1266a0d31df90801729ec0c1f53 @dduponchel dduponchel committed Nov 26, 2011
Showing with 953 additions and 432 deletions.
  1. +229 −69 index.html
  2. +3 −0 jszip-inflate.js
  3. +1 −1 jszip-load.js
  4. +464 −312 jszip.js
  5. +256 −50 test/index.html
  6. 0 test/ref/utf8.zip
View
298 index.html
@@ -74,6 +74,12 @@
border-top: 1px solid #CCCCCC;
}
+dt
+{
+ /*font-weight:bold;*/
+ text-decoration:underline;
+}
+
#where p
{
text-align: center;
@@ -146,9 +152,9 @@
<h2>How?</h2>
<textarea id="demo-code" rows="7" class="grid_5 alpha omega" spellcheck="false">
var zip = new JSZip();
-zip.add("Hello.txt", "Hello World\n");
+zip.file("Hello.txt", "Hello World\n");
img = zip.folder("images");
-img.add("smile.gif", imgData, {base64: true});
+img.file("smile.gif", imgData, {base64: true});
content = zip.generate();
location.href="data:application/zip;base64,"+content;
</textarea>
@@ -179,7 +185,9 @@
<div class="grid_9 border">
<h2>Tell me more!</h2>
- <h3>Browser support</h3>
+ <p>While JSZip should work everywhere, the tricky part is to give the zip file to the user.</p>
+
+ <h3>Browser support for <a href="https://en.wikipedia.org/wiki/Data_URI_scheme">data URI scheme</a> with zip</h3>
<table cellspacing="0">
<tr><th class="op">Opera</th> <th class="ff">Firefox</th> <th class="sf">Safari</th> <th class="cr">Chrome</th> <th class="ie">Internet Explorer</th> </tr>
<tr><td>7.5+</td> <td>3.0+</td> <td>Yes</td> <td>Yes</td> <td>No</td></tr>
@@ -218,99 +226,251 @@
<h2 style="margin-top: 2em;">Documentation</h2>
- <h4>new JSZip([compressionMethod])</h4>
- <p>The constructor</p>
- <p><code>compressionMethod</code>, string. The compression method to use for the zip file.</p>
- <p>
- Available methods :
- <ul>
- <li><code>"STORE"</code> no compression, the default.</li>
- <li><code>"DEFLATE"</code> default zip compression, need the file jszip-deflate.js</li>
- </ul>
- </p>
+ <h4 id="JSZip()">new JSZip()</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>The default constructor.</dd>
+ <dt>Returns : </dt>
+ <dd>A new JSZip.</dd>
+ </dl>
+
+ <h4 id="new JSZip(data [,options])">new JSZip(data [,options])</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Create a new JSZip file and load an existing zip file. See the documentation of <a href="#load(data, options)"><code>load()</code></a> for more details.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>data</code> (String/binary) the content of the zip file to load.</dd>
+ <dd><code>options</code> (Object) options to pass to the <a href="#load(data, options)"><code>load()</code></a> method..</dd>
+ <dt>Returns : </dt>
+ <dd>A new JSZip.</dd>
+ </dl>
<pre class="example">
-var zip = new JSZip(); // same as new JSZip("STORE");
-var zip = new JSZip("DEFLATE");</pre>
-
- <h4>add(name, data [,options])</h4>
- <p>Add a file to the zip file. Supports chaining.</p>
- <p>Options:</p>
- <ul>
- <li><code>base64</code>, boolean. Set to <code>true</code> if the data
- is base64 encoded. For example image data from a <code>&lt;canvas&gt;</code> element.
- Plain text and HTML do not need this option.</li>
- <li><code>binary</code>, boolean. Defaults to <code>true</code> if the data
- is base64 encoded, <code>false</code> otherwise. If set to false then
- UTF-8 characters will be encoded.</li>
- <li><code>date</code>, Date. Use it to specify the last modification date.
- If not set the current date is used.</li>
- </ul>
+new JSZip(zipDataFromXHR, {base64:false});
+// same as
+var zip = new JSZip();
+zip.load(zipDataFromXHR, {base64:false});</pre>
+
+ <h4 id="file(name)">file(name)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Get a file with the specified name.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>name</code> (String) the name of the file.</dd>
+ <dt>Returns : </dt>
+ <dd>The file if any, <code>null</code> otherwise. The file has the following structure :
+ <ul>
+ <li><code>name</code> the absolute path of the file</li>
+ <li><code>data</code> the data contained in the file</li>
+ <li><code>options</code> the options of the file. The available options are :
+ <ul>
+ <li><code>base64</code>, boolean, cf <a href="#file(name, data [,options])">file(name, data [,options])</a></li>
+ <li><code>binary</code>, boolean, cf <a href="#file(name, data [,options])">file(name, data [,options])</a></li>
+ <li><code>dir</code>, boolean, true if this is a directory</li>
+ <li><code>date</code>, date, <a href="#file(name, data [,options])">file(name, data [,options])</a></li>
+ </ul>
+ </li>
+ </ul>
+ </dd>
+ </dl>
+ <pre class="example">
+var zip = new JSZip();
+zip.file("file.txt", "content");
+
+zip.file("file.txt").name // "file.txt"
+zip.file("file.txt").data // "content"
+zip.file("file.txt").options.dir // false</pre>
+
+ <h4 id="file(regex)">file(regex)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Search a file in the current folder and subfolders with a <a href="http://www.javascriptkit.com/javatutors/redev.shtml">regular expression</a>. The regex is tested against the relative filename.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>regex</code> (RegExp) the regex to use.</dd>
+ <dt>Returns : </dt>
+ <dd>An array of matching files (an empty array if none matched).</dd>
+ </dl>
+ <pre class="example">
+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", data: "content", dir: false}</pre>
+
+ <h4 id="file(name, data [,options])">file(name, data [,options])</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Add a file to the zip file.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>name</code> (String) the name of the file.</dd>
+ <dd><code>data</code> (binary) the content of the file.</dd>
+ <dd><code>options</code> (Object) the options :
+ <ul>
+ <li><code>base64</code> (boolean) set to <code>true</code> if the data
+ is base64 encoded. For example image data from a <code>&lt;canvas&gt;</code> element.
+ Plain text and HTML do not need this option.</li>
+ <li><code>binary</code> (boolean) defaults to <code>true</code> if the data
+ is base64 encoded, <code>false</code> otherwise. If set to false then
+ UTF-8 characters will be encoded.</li>
+ <li><code>date</code> (Date) use it to specify the last modification date.
+ If not set the current date is used.</li>
+ </ul>
+ </dd>
+ <dt>Returns : </dt>
+ <dd>A JSZip object, for chaining.</dd>
+ </dl>
<pre class="example">
zip.add("Hello.txt", "Hello World\n");
zip.add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
zip.add("magic.txt", "U2VjcmV0IGNvZGU=", {base64: true, binary: false});
zip.add("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
-
-zip.add("animals.txt", "dog,platypus\n").add("people.txt", "james,sebastian\n");</pre>
- <p>
- Result: <code>Hello.txt, smile.gif, magic.txt, Xmas.txt, animals.txt, people.txt</code>
- </p>
-
- <h4>folder(name)</h4>
- <p>Add a directory to the zip file. Supports chaining.</p>
+zip.add("folder/file.txt", "file in folder");
+
+zip.add("animals.txt", "dog,platypus\n").add("people.txt", "james,sebastian\n");
+
+// result : Hello.txt, smile.gif, magic.txt, Xmas.txt, animals.txt, people.txt,
+// folder/, folder/file.txt</pre>
+
+ <h4 id="folder(name)">folder(name)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Add a directory to the zip file.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>name</code> (String) the name of the directory.</dd>
+ <dt>Returns : </dt>
+ <dd>a new JSZip (for chaining), with the new folder as root.</dd>
+ </dl>
<pre class="example">
zip.folder("images");
zip.folder("css").add("style.css", "body {background: #FF0000}");
// or specify an absolute path (using forward slashes)
-zip.add("css/font.css", "body {font-family: sans-serif}")</pre>
- <p>
- Result: <code>images/, css/, css/style.css, css/font.css</code>
- </p>
-
- <h4>find(needle)</h4>
- <p>Compare a string or <a href="http://www.javascriptkit.com/javatutors/redev.shtml">regular expression</a>
- against all of the filenames and returns an informational object for each that matches.</p>
+zip.add("css/font.css", "body {font-family: sans-serif}")
+
+// result : images/, css/, css/style.css, css/font.css</pre>
+
+ <h4 id="folder(regex)">folder(regex)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Search a subdirectory.</dd>
+ <dd>Search a subdirectory in the current directory with a <a href="http://www.javascriptkit.com/javatutors/redev.shtml">regular expression</a>. The regex is tested against the relative path.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>regex</code> (RegExp) the regex to use.</dd>
+ <dt>Returns : </dt>
+ <dd>An array of matching folders (an empty array if none matched).</dd>
+ </dl>
<pre class="example">
-zip.add("Readme", "Hello World!\n");
-zip.add("Readme.French", "Bonjour tout le monde!\n");
-zip.add("Readme.Pirate", "Ahoy m'hearty!\n");
+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.find("Readme"); // only finds "Readme"
-zip.find(/^Readme/); // Regular expression finds all three</pre>
- <p>
- Result: Array of matched file objects in the form:
- <code>{name: "Readme", data: "Hello World!", dir: false}</code>
- </p>
+zip.folder(/videos/); // array of size 2
- <h4>remove(name)</h4>
+zip.folder("home/Jean").folder(/^vid/); // array of 1</pre>
+
+ <h4 id="remove(name)">remove(name)</h4>
<p>Delete a file or folder.</p>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Delete a file or folder (recursively).</dd>
+ <dt>Parameters : </dt>
+ <dd><code>name</code> (String) the name of the file/folder to delete.</dd>
+ <dt>Returns : </dt>
+ <dd>The current JSZip object.</dd>
+ </dl>
<pre class="example">
+var zip = new JSZip();
zip.add("Hello.txt", "Hello World\n");
-zip.add("temp.txt", "nothing").remove("temp.txt");</pre>
- <p>
- Result: <code>Hello.txt</code>
- </p>
- <pre class="example">
-zip.add("Hello.txt", "Hello World\n");
-zip.folder("css").add("style.css", "body {background: #FF0000}");
-zip.remove("Hello.txt").remove("css");</pre>
- <p>
- Result: Empty zip.
- </p>
+zip.add("temp.txt", "nothing").remove("temp.txt");
+// result : Hello.txt
- <h4>generate(asBytes = false)</h4>
- <p>Generates the complete zip file. By default encoded as base64, pass <code>true</code> to get the raw byte string</p>
+zip.folder("css").add("style.css", "body {background: #FF0000}");
+zip.remove("Hello.txt").remove("css");
+//result : empty zip</pre>
+
+ <h4 id="generate(options)">generate(options)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Generates the complete zip file.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>options</code> (Object) the options to generate the zip file :
+ <ul>
+ <li><code>base64</code> (boolean) <code>false</code> to get the result as a raw byte string.
+ Default : <code>true</code>, encode as base64.</li>
+ <li><code>compression</code> (String) the compression method to use. <code>"STORE"</code> (no compression) by default,
+ you can use <code>"DEFLATE"</code> (include the file jszip-deflate.js) or write your own.</li>
+ </ul>
+ </dd>
+ <dt>Returns : </dt>
+ <dd>The generated zip file.</dd>
+ </dl>
<pre class="example">
content = zip.generate();
location.href="data:application/zip;base64,"+content;</pre>
<pre class="example">
-content = zip.generate(true);
+content = zip.generate({base64:false});
for (var c = 0; c &lt; content.length; c++)
{
console.log(content.charCodeAt(c));
// do other things
}</pre>
+
+ <h4 id="load(data, options)">load(data, options)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Read an existing zip and merge the data in the current JSZip object. The implementation is in jszip-load.js, don't forget to include it.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>data</code> (binary) the zip file</dd>
+ <dd><code>options</code> (Object) the options to load the zip file :
+ <ul>
+ <li><code>base64</code> (boolean) <code>true</code> if the data is base64 encoded, <code>false</code> for binary. Default : <code>false</code>.</li>
+ </ul>
+ </dd>
+ <dt>Returns : </dt>
+ <dd>The current JSZip object.</dd>
+ </dl>
+ <pre class="example">
+var zip = new JSZip();
+zip.load(zipDataFromXHR);</pre>
+
+ <h4 id="filter(predicate)">filter(predicate)</h4>
+ <dl>
+ <dt>Description : </dt>
+ <dd>Filter nested files/folders with the specified function.</dd>
+ <dt>Parameters : </dt>
+ <dd><code>predicate</code> (function) the predicate to use : <code>function (relativePath, file) {...}</code> It takes 2 arguments : the relative path and the file.
+ <ul>
+ <li><code>relativePath</code> (String) The filename and its path, reliatively to the current folder.</li>
+ <li><code>file</code> (Object) The file being tested. Like the result of <a href="#file(name)"><code>file(name)</code></a>, the file has the form <code>{name:"...", data:"...", options:{...}}</code>.</li>
+ <li>Return true if the file should be included, false otherwise.</li>
+ </ul>
+ </dd>
+ <dt>Returns : </dt>
+ <dd>An array of matching elements.</dd>
+ </dl>
+ <pre class="example">
+var zip = new JSZip().folder("dir");
+zip.file("readme.txt", "content");
+zip.filter(function (relativePath, file){
+ // relativePath == "readme.txt"
+ // file = {name:"dir/readme.txt",data:"content",options:{...}}
+ return true/false;
+});
+</pre>
+
</div>
<div id="who" class="grid_3">
View
3 jszip-inflate.js
@@ -19,6 +19,9 @@ if(!JSZip)
*/
(function(){
+ // the original implementation leaks a global variable.
+ // Defining the variable here doesn't break anything.
+ var zip_fixed_bd;
/* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0.0.1
View
2 jszip-load.js
@@ -383,7 +383,7 @@ Licenced under the GPLv3 and the MIT licences
for (i in files)
{
input = files[i];
- this.add(input.fileName, input.uncompressedFileData, {
+ this.file(input.fileName, input.uncompressedFileData, {
binary:true,
date:input.date,
dir:input.dir
View
776 jszip.js
@@ -8,302 +8,516 @@ Licenced under the GPLv3 and the MIT licences
Usage:
zip = new JSZip();
- zip.add("hello.txt", "Hello, World!").add("tempfile", "nothing");
- zip.folder("images").add("smile.gif", base64Data, {base64: true});
- zip.add("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
+ zip.file("hello.txt", "Hello, World!").add("tempfile", "nothing");
+ zip.folder("images").file("smile.gif", base64Data, {base64: true});
+ zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
zip.remove("tempfile");
base64zip = zip.generate();
**/
-function JSZip(compression)
+var JSZip = function(data, options)
{
- // default : no compression
- this.compression = (compression || "STORE").toUpperCase();
this.files = [];
// Where we are in the hierarchy
this.root = "";
- // Default properties for a new file
- this.d = {
- base64: false,
- binary: false,
- dir: false,
- date: null
- };
-
- if (!JSZip.compressions[this.compression]) {
- throw compression + " is not a valid compression method !";
- }
+ if(data) this.load(data, options);
}
JSZip.signature = {
- LOCAL_FILE_HEADER : "\x50\x4b\x03\x04",
- CENTRAL_FILE_HEADER : "\x50\x4b\x01\x02",
- CENTRAL_DIRECTORY_END : "\x50\x4b\x05\x06"
+ LOCAL_FILE_HEADER : "\x50\x4b\x03\x04",
+ CENTRAL_FILE_HEADER : "\x50\x4b\x01\x02",
+ CENTRAL_DIRECTORY_END : "\x50\x4b\x05\x06"
};
-/**
- * Load a zip stream into the current JSZip object.
- * @param stream The stream to load
- * @param options Options for loading the stream.
- * options.base64 : is the stream in base64 ? default : false
- * @return this JSZip object
- */
-JSZip.prototype.load = function (stream, options)
-{
- throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
+// Default properties for a new file
+JSZip.defaults = {
+ base64: false,
+ binary: false,
+ dir: false,
+ date: null
};
-/**
- * Add a file to the zip file
- * @param name The name of the file
- * @param data The file data, either raw or base64 encoded
- * @param o File options
- * @return this JSZip object
- */
-JSZip.prototype.add = function(name, data, o)
+
+JSZip.prototype = (function ()
{
- o = o || {};
- name = this.root+name;
+ /**
+ * Transform an integer into a string in hexadecimal.
+ * @private
+ * @param {Number} dec the number to convert.
+ * @param {Number} bytes the number of bytes to generate.
+ * @returns {String} the result.
+ */
+ var decToHex = function(dec, bytes)
+ {
+ var hex = "", i;
+ for(i = 0; i < bytes; i++)
+ {
+ hex += String.fromCharCode(dec&0xff);
+ dec=dec>>>8;
+ }
+ return hex;
+ };
- if (o.base64 === true && o.binary == null) o.binary = true;
+ /**
+ * Merge the objects passed as parameters into a new one.
+ * @private
+ * @return {Object} a new object with the data of the others.
+ */
+ var extend = function ()
+ {
+ var result = {}, i, attr;
+ for (i = 0; i < arguments.length; i++) // arguments is not enumerable in some browsers
+ {
+ for (attr in arguments[i])
+ {
+ if(typeof result[attr] === "undefined")
+ {
+ result[attr] = arguments[i][attr];
+ }
+ }
+ }
+ return result;
+ };
- for (var opt in this.d)
+ /**
+ * Transforms the (incomplete) options from the user into the complete
+ * set of options to create a file.
+ * @private
+ * @param {Object} o the options from the user.
+ * @return {Object} the complete set of options.
+ */
+ var prepareFileAttrs = function (o)
{
- o[opt] = o[opt] || this.d[opt];
+ o = o || {};
+ if (o.base64 === true && o.binary == null) o.binary = true;
+ o = extend(o, JSZip.defaults);
+ o.date = o.date || new Date();
+
+ return o;
}
- // date
- // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
- // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
- // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
-
- o.date = o.date || new Date();
- var dosTime, dosDate;
-
- dosTime = o.date.getHours();
- dosTime = dosTime << 6;
- dosTime = dosTime | o.date.getMinutes();
- dosTime = dosTime << 5;
- dosTime = dosTime | o.date.getSeconds() / 2;
-
- dosDate = o.date.getFullYear() - 1980;
- dosDate = dosDate << 4;
- dosDate = dosDate | (o.date.getMonth() + 1);
- dosDate = dosDate << 5;
- dosDate = dosDate | o.date.getDate();
-
- if (o.base64 === true) data = JSZipBase64.decode(data);
- // decode UTF-8 strings if we are dealing with text data
- if(o.binary === false) data = this.utf8encode(data);
-
-
- var compression = JSZip.compressions[this.compression];
- var compressedData = compression.compress(data);
-
- var header = "";
-
- // version needed to extract
- header += "\x0A\x00";
- // general purpose bit flag
- header += "\x00\x00";
- // compression method
- header += compression.magic;
- // last mod file time
- header += this.decToHex(dosTime, 2);
- // last mod file date
- header += this.decToHex(dosDate, 2);
- // crc-32
- header += this.decToHex(this.crc32(data), 4);
- // compressed size
- header += this.decToHex(compressedData.length, 4);
- // uncompressed size
- header += this.decToHex(data.length, 4);
- // file name length
- header += this.decToHex(name.length, 2);
- // extra field length
- header += "\x00\x00";
-
- // file name
-
- this.files[name] = {header: header, data: compressedData, dir: o.dir};
-
- return this;
-};
+ /**
+ * Add a file in the current folder.
+ * @private
+ * @param {String} name the name of the file
+ * @param {String} data the data of the file
+ * @param {Object} o the options of the file
+ * @return {Object} the new file.
+ */
+ var fileAdd = function (name, data, o)
+ {
+ // be sure sub folders exist
+ var parent = parentFolder(name);
+ if (parent) folderAdd.call(this, parent);
-/**
- * Add a directory to the zip file
- * @param name The name of the directory to add
- * @return JSZip object with the new directory as the root
- */
-JSZip.prototype.folder = function(name)
-{
- // Check the name ends with a /
- if (name.substr(-1) != "/") name += "/";
+ o = prepareFileAttrs(o);
- // Does this folder already exist?
- if (typeof this.files[name] === "undefined") this.add(name, '', {dir:true});
+ return this.files[name] = {name: name, data: data, options:o};
+ };
- // Allow chaining by returning a new object with this folder as the root
- var ret = this.clone();
- ret.root = this.root+name;
- return ret;
-};
-/**
- * Compare a string or regular expression against all of the filenames and
- * return an informational object for each that matches.
- * @param string/regex The regular expression to test against
- * @return An array of objects representing the matched files. In the form
- * {name: "filename", data: "file data", dir: true/false}
- */
-JSZip.prototype.find = function(needle)
-{
- var result = [], re;
- if (typeof needle === "string")
+ /**
+ * Find the parent folder of the path.
+ * @private
+ * @param {String} path the path to use
+ * @return {String} the parent folder, or ""
+ */
+ var parentFolder = function (path)
{
- re = new RegExp("^"+needle+"$");
- }
- else
- {
- re = needle;
- }
+ if (path.slice(-1) == '/')
+ {
+ path = path.substring(0, path.length - 1);
+ }
+ var lastSlash = path.lastIndexOf('/');
+ return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
+ };
- for (var filename in this.files)
+ /**
+ * Add a (sub) folder in the current folder.
+ * @private
+ * @param {String} name the folder's name
+ * @return {Object} the new folder.
+ */
+ var folderAdd = function (name)
{
- if (re.test(filename))
+ // Check the name ends with a /
+ if (name.slice(-1) != "/") name += "/"; // IE doesn't like substr(-1)
+
+ // Does this folder already exist?
+ if (!this.files[name])
{
- var file = this.files[filename];
- result.push({name: filename, data: file.data, dir: !!file.dir});
- }
- }
+ // be sure sub folders exist
+ var parent = parentFolder(name);
+ if (parent) folderAdd.call(this, parent);
- return result;
-};
+ fileAdd.call(this, name, '', {dir:true});
+ }
+ return this.files[name];
+ };
-/**
- * Delete a file, or a directory and all sub-files, from the zip
- * @param name the name of the file to delete
- * @return this JSZip object
- */
-JSZip.prototype.remove = function(name)
-{
- var file = this.files[name];
- if (!file)
+ /**
+ * Generate the data found in the local header of a zip file.
+ * Do not create it now, as some parts are re-used later.
+ * @private
+ * @param {Object} file the file to use.
+ * @param {String} compressionType the compression to use.
+ * @return {Object} an object containing header and compressedData.
+ */
+ var prepareLocalHeaderData = function(file, compressionType)
{
- // Look for any folders
- if (name.substr(-1) != "/") name += "/";
- file = this.files[name];
- }
+ var name = file.name,
+ data = file.data,
+ o = file.options,
+ dosTime, dosDate;
+
+ // date
+ // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
+ // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
+ // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
+
+ dosTime = o.date.getHours();
+ dosTime = dosTime << 6;
+ dosTime = dosTime | o.date.getMinutes();
+ dosTime = dosTime << 5;
+ dosTime = dosTime | o.date.getSeconds() / 2;
+
+ dosDate = o.date.getFullYear() - 1980;
+ dosDate = dosDate << 4;
+ dosDate = dosDate | (o.date.getMonth() + 1);
+ dosDate = dosDate << 5;
+ dosDate = dosDate | o.date.getDate();
+
+ if (o.base64 === true) data = JSZipBase64.decode(data);
+ // decode UTF-8 strings if we are dealing with text data
+ if(o.binary === false) data = this.utf8encode(data);
+
+
+ var compression = JSZip.compressions[compressionType];
+ var compressedData = compression.compress(data);
+
+ var header = "";
+
+ // version needed to extract
+ header += "\x0A\x00";
+ // general purpose bit flag
+ header += "\x00\x00";
+ // compression method
+ header += compression.magic;
+ // last mod file time
+ header += decToHex(dosTime, 2);
+ // last mod file date
+ header += decToHex(dosDate, 2);
+ // crc-32
+ header += decToHex(this.crc32(data), 4);
+ // compressed size
+ header += decToHex(compressedData.length, 4);
+ // uncompressed size
+ header += decToHex(data.length, 4);
+ // file name length
+ header += decToHex(name.length, 2);
+ // extra field length
+ header += "\x00\x00";
+
+ return {
+ header:header,
+ compressedData:compressedData
+ };
+ };
- if (file)
- {
- if (name.match("/") === null)
+
+ // return the actual prototype of JSZip
+ return {
+ /**
+ * Read an existing zip and merge the data in the current JSZip object.
+ * The implementation is in jszip-load.js, don't forget to include it.
+ * @param {Binary} stream The stream to load
+ * @param {Object} options Options for loading the stream.
+ * options.base64 : is the stream in base64 ? default : false
+ * @return {JSZip} the current JSZip object
+ */
+ load : function (stream, options)
{
- // file
- delete this.files[name];
- }
- else
+ throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
+ },
+
+ /**
+ * Filter nested files/folders with the specified function.
+ * @param {Function} search the predicate to use :
+ * function (relativePath, file) {...}
+ * It takes 2 arguments : the relative path and the file.
+ * @return {Array} An array of matching elements.
+ */
+ filter : function (search)
+ {
+ var result = [], filename, relativePath, file, fileClone;
+ for (filename in this.files)
+ {
+ file = this.files[filename];
+ // return a new object, don't let the user mess with our internal objects :)
+ fileClone = {
+ name:file.name,
+ data:file.data,
+ options:extend(file.options)
+ };
+ relativePath = filename.slice(this.root.length, filename.length);
+ if (filename.slice(0, this.root.length) === this.root // the file is in the current root
+ && search(relativePath, fileClone)) // and the file matches the function
+ {
+ result.push(fileClone);
+ }
+ }
+ return result;
+ },
+
+ /**
+ * Add a file to the zip file, or search a file.
+ * @param {String|Regexp} name The name of the file to add (if data is defined),
+ * the name of the file to find (if no data) or a regex to match files.
+ * @param {binary} data The file data, either raw or base64 encoded
+ * @param {Object} o File options
+ * @return {JSZip|Object|Array} this JSZip object (when adding a file),
+ * a file (when searching by string) or an array of files (when searching by regex).
+ */
+ file : function(name, data, o)
+ {
+ if (arguments.length === 1)
+ {
+ if (name instanceof RegExp)
+ {
+ var regexp = name;
+ return this.filter(function(relativePath, file) {
+ return !file.options.dir && regexp.test(relativePath);
+ });
+ }
+ else // text
+ {
+ return this.filter(function (relativePath, file) {
+ return !file.options.dir && relativePath === name;
+ })[0]||null;
+ }
+ }
+ else // more than one argument : we have data !
+ {
+ name = this.root+name;
+ fileAdd.call(this, name, data, o);
+ }
+ return this;
+ },
+
+ /**
+ * Add a directory to the zip file, or search.
+ * @param {String|Regexp} arg The name of the directory to add, or a regex to search folders.
+ * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
+ */
+ folder : function(arg)
+ {
+ if (!arg)
+ {
+ throw new Error("folder : wrong argument");
+ }
+
+ if (arg instanceof RegExp)
+ {
+ return this.filter(function(relativePath, file) {
+ return file.options.dir && arg.test(relativePath);
+ });
+ }
+
+ // else, name is a new folder
+ var name = this.root + arg;
+ var newFolder = folderAdd.call(this, name);
+
+ // Allow chaining by returning a new object with this folder as the root
+ var ret = this.clone();
+ ret.root = newFolder.name;
+ return ret;
+ },
+
+ /**
+ * Delete a file, or a directory and all sub-files, from the zip
+ * @param {String} name the name of the file to delete
+ * @return {JSZip} this JSZip object
+ */
+ remove : function(name)
{
- // folder
- var kids = this.find(new RegExp("^"+name));
- for (var i = 0; i < kids.length; i++)
+ name = this.root + name;
+ var file = this.files[name];
+ if (!file)
{
- if (kids[i].name == name)
+ // Look for any folders
+ if (name.slice(-1) != "/") name += "/";
+ file = this.files[name];
+ }
+
+ if (file)
+ {
+ if (!file.options.dir)
{
- // Delete this folder
+ // file
delete this.files[name];
}
else
{
- // Remove a child of this folder
- this.remove(kids[i].name);
+ // folder
+ var kids = this.filter(function (relativePath, file) {
+ return file.name.slice(0, name.length) === name;
+ });
+ for (var i = 0; i < kids.length; i++)
+ {
+ delete this.files[kids[i].name];
+ }
}
}
- }
- }
- return this;
-};
+ return this;
+ },
-/**
- * Generate the complete zip file
- * @return A base64 encoded string of the zip file
- */
-JSZip.prototype.generate = function(asBytes)
-{
- asBytes = asBytes || false;
+ /**
+ * Generate the complete zip file
+ * @param {Object} options the options to generate the zip file :
+ * - base64, true to generate base64.
+ * - compression, "STORE" by default.
+ * @return {String} the zip file
+ */
+ generate : function(options)
+ {
+ options = extend(options || {}, {
+ base64 : true,
+ compression : "STORE"
+ });
+ var compression = options.compression.toUpperCase();
- // The central directory, and files data
- var directory = [], files = [], fileOffset = 0;
+ // The central directory, and files data
+ var directory = [], files = [], fileOffset = 0;
- for (var name in this.files)
- {
- if( !this.files.hasOwnProperty(name) ) { continue; }
-
- var fileRecord = "", dirRecord = "";
- fileRecord = JSZip.signature.LOCAL_FILE_HEADER + this.files[name].header + name + this.files[name].data;
-
- dirRecord = JSZip.signature.CENTRAL_FILE_HEADER +
- // version made by (00: DOS)
- "\x14\x00" +
- // file header (common to file and central directory)
- this.files[name].header +
- // file comment length
- "\x00\x00" +
- // disk number start
- "\x00\x00" +
- // internal file attributes TODO
- "\x00\x00" +
- // external file attributes
- (this.files[name].dir===true?"\x10\x00\x00\x00":"\x00\x00\x00\x00")+
- // relative offset of local header
- this.decToHex(fileOffset, 4) +
- // file name
- name;
-
- fileOffset += fileRecord.length;
-
- files.push(fileRecord);
- directory.push(dirRecord);
- }
+ if (!JSZip.compressions[compression]) {
+ throw compression + " is not a valid compression method !";
+ }
- var fileData = files.join("");
- var dirData = directory.join("");
-
- var dirEnd = "";
-
- // end of central dir signature
- dirEnd = JSZip.signature.CENTRAL_DIRECTORY_END +
- // number of this disk
- "\x00\x00" +
- // number of the disk with the start of the central directory
- "\x00\x00" +
- // total number of entries in the central directory on this disk
- this.decToHex(files.length, 2) +
- // total number of entries in the central directory
- this.decToHex(files.length, 2) +
- // size of the central directory 4 bytes
- this.decToHex(dirData.length, 4) +
- // offset of start of central directory with respect to the starting disk number
- this.decToHex(fileData.length, 4) +
- // .ZIP file comment length
- "\x00\x00";
-
- var zip = fileData + dirData + dirEnd;
- return (asBytes) ? zip : JSZipBase64.encode(zip);
+ for (var name in this.files)
+ {
+ if( !this.files.hasOwnProperty(name) ) { continue; }
+
+ var fileRecord = "",
+ dirRecord = "",
+ data = prepareLocalHeaderData.call(this, this.files[name], compression);
+ fileRecord = JSZip.signature.LOCAL_FILE_HEADER + data.header + name + data.compressedData;
+
+ dirRecord = JSZip.signature.CENTRAL_FILE_HEADER +
+ // version made by (00: DOS)
+ "\x14\x00" +
+ // file header (common to file and central directory)
+ data.header +
+ // file comment length
+ "\x00\x00" +
+ // disk number start
+ "\x00\x00" +
+ // internal file attributes TODO
+ "\x00\x00" +
+ // external file attributes
+ (this.files[name].dir===true?"\x10\x00\x00\x00":"\x00\x00\x00\x00")+
+ // relative offset of local header
+ decToHex(fileOffset, 4) +
+ // file name
+ name;
+
+ fileOffset += fileRecord.length;
+
+ files.push(fileRecord);
+ directory.push(dirRecord);
+ }
-};
+ var fileData = files.join("");
+ var dirData = directory.join("");
+
+ var dirEnd = "";
+
+ // end of central dir signature
+ dirEnd = JSZip.signature.CENTRAL_DIRECTORY_END +
+ // number of this disk
+ "\x00\x00" +
+ // number of the disk with the start of the central directory
+ "\x00\x00" +
+ // total number of entries in the central directory on this disk
+ decToHex(files.length, 2) +
+ // total number of entries in the central directory
+ decToHex(files.length, 2) +
+ // size of the central directory 4 bytes
+ decToHex(dirData.length, 4) +
+ // offset of start of central directory with respect to the starting disk number
+ decToHex(fileData.length, 4) +
+ // .ZIP file comment length
+ "\x00\x00";
+
+ var zip = fileData + dirData + dirEnd;
+ return (options.base64) ? JSZipBase64.encode(zip) : zip;
+ },
+
+ /**
+ *
+ * Javascript crc32
+ * http://www.webtoolkit.info/
+ *
+ */
+ crc32 : function(str, crc)
+ {
+
+ if (str === "") return "\x00\x00\x00\x00";
+
+ var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
+
+ if (typeof(crc) == "undefined") { crc = 0; }
+ var x = 0;
+ var y = 0;
+
+ crc = crc ^ (-1);
+ for( var i = 0, iTop = str.length; i < iTop; i++ ) {
+ y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
+ x = "0x" + table.substr( y * 9, 8 );
+ crc = ( crc >>> 8 ) ^ x;
+ }
+
+ return crc ^ (-1);
+
+ },
+
+ // Inspired by http://my.opera.com/GreyWyvern/blog/show.dml/1725165
+ clone : function()
+ {
+ var newObj = new JSZip();
+ for (var i in this)
+ {
+ if (typeof this[i] !== "function")
+ {
+ newObj[i] = this[i];
+ }
+ }
+ return newObj;
+ },
+
+ utf8encode : function(input)
+ {
+ input = encodeURIComponent(input);
+ input = input.replace(/%.{2,2}/g, function(m) {
+ var hex = m.substring(1);
+ return String.fromCharCode(parseInt(hex,16));
+ });
+ return input;
+ }
+ };
+})();
/*
* Compression methods
* This object is filled in as follow :
* name : {
* magic // the 2 bytes indentifying the compression method
* compress // function, take the uncompressed content and return it compressed.
+ * uncompress // function, take the compressed content and return it uncompressed.
* }
*
* STORE is the default compression method, so it's included in this file.
@@ -312,88 +526,24 @@ JSZip.prototype.generate = function(asBytes)
JSZip.compressions = {
"STORE" : {
magic : "\x00\x00",
- compress : function (content) {
+ compress : function (content)
+ {
return content; // no compression
},
- uncompress : function (content) {
- return content; // no compression
- }
- }
-};
-
-// Utility functions
-
-JSZip.prototype.decToHex = function(dec, bytes)
-{
- var hex = "";
- for(var i=0;i<bytes;i++) {
- hex += String.fromCharCode(dec&0xff);
- dec=dec>>>8;
- }
- return hex;
-};
-
-/**
-*
-* Javascript crc32
-* http://www.webtoolkit.info/
-*
-**/
-
-JSZip.prototype.crc32 = function(str, crc)
-{
-
- if (str === "") return "\x00\x00\x00\x00";
-
- var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
-
- if (typeof(crc) == "undefined") { crc = 0; }
- var x = 0;
- var y = 0;
-
- crc = crc ^ (-1);
- for( var i = 0, iTop = str.length; i < iTop; i++ ) {
- y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
- x = "0x" + table.substr( y * 9, 8 );
- crc = ( crc >>> 8 ) ^ x;
- }
-
- return crc ^ (-1);
-
-};
-
-// Inspired by http://my.opera.com/GreyWyvern/blog/show.dml/1725165
-JSZip.prototype.clone = function()
-{
- var newObj = new JSZip();
- for (var i in this)
- {
- if (typeof this[i] !== "function")
+ uncompress : function (content)
{
- newObj[i] = this[i];
+ return content; // no compression
}
}
- return newObj;
-};
-
-JSZip.prototype.utf8encode = function(input)
-{
- input = encodeURIComponent(input);
- input = input.replace(/%.{2,2}/g, function(m) {
- var hex = m.substring(1);
- return String.fromCharCode(parseInt(hex,16));
- });
- return input;
};
/**
-*
-* Base64 encode / decode
-* http://www.webtoolkit.info/
-*
-* Hacked so that it doesn't utf8 en/decode everything
-**/
-
+ *
+ * Base64 encode / decode
+ * http://www.webtoolkit.info/
+ *
+ * Hacked so that it doesn't utf8 en/decode everything
+ **/
var JSZipBase64 = function() {
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
@@ -423,8 +573,8 @@ var JSZipBase64 = function() {
}
output = output +
- _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
- _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
+ _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
+ _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
@@ -467,3 +617,5 @@ var JSZipBase64 = function() {
}
};
}();
+
+// vim: set shiftwidth=3 softtabstop=3:
View
306 test/index.html
@@ -27,7 +27,7 @@
function reload(bytesStream)
{
- var content = new JSZip().load(bytesStream, true).generate();
+ var content = new JSZip(bytesStream).generate();
var actual = JSZipBase64.decode(content);
return actual;
}
@@ -57,8 +57,33 @@
var expected = refZips["text"];
var zip = new JSZip();
- zip.add("Hello.txt", "Hello World\n");
- content = zip.generate();
+ zip.file("Hello.txt", "Hello World\n");
+ var content = zip.generate();
+
+ var actual = JSZipBase64.decode(content);
+
+ /*
+ Expected differing bytes:
+ 2 version number
+ 4 date/time
+ 4 central dir version numbers
+ 4 central dir date/time
+ 4 external file attributes
+
+ 18 Total
+ */
+ ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
+ });
+
+ test("Add a file to overwrite", function()
+ {
+ var expected = refZips["text"];
+
+ var zip = new JSZip();
+ zip.file("Hello.txt", "hello ?");
+ zip.file("Hello.txt", "Hello World\n");
+ var content = zip.generate();
var actual = JSZipBase64.decode(content);
@@ -81,8 +106,8 @@
var expected = refZips["utf8"];
var zip = new JSZip();
- zip.add("amount.txt", "€15\n");
- content = zip.generate();
+ zip.file("amount.txt", "€15\n");
+ var content = zip.generate();
var actual = JSZipBase64.decode(content);
@@ -95,8 +120,8 @@
var expected = refZips["text"];
var zip = new JSZip();
- zip.add("Hello.txt", "Hello World\n", {date : new Date("July 17, 2009 14:36:57")});
- content = zip.generate();
+ zip.file("Hello.txt", "Hello World\n", {date : new Date("July 17, 2009 14:36:57")});
+ var content = zip.generate();
var actual = JSZipBase64.decode(content);
@@ -118,10 +143,10 @@
var expected = refZips["image"];
var zip = new JSZip();
- zip.add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
- content = zip.generate();
+ zip.file("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
+ var content = zip.generate();
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
equals(reload(actual), actual, "Generated ZIP can be parsed");
@@ -133,9 +158,9 @@
var zip = new JSZip();
zip.folder("folder");
- content = zip.generate();
+ var content = zip.generate();
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
equals(reload(actual), actual, "Generated ZIP can be parsed");
@@ -146,11 +171,11 @@
var expected = refZips["all"];
var zip = new JSZip();
- zip.add("Hello.txt", "Hello World\n");
- zip.folder("images").add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
- content = zip.generate();
+ zip.file("Hello.txt", "Hello World\n");
+ zip.folder("images").file("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
+ var content = zip.generate();
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
/*
Expected differing bytes:
@@ -172,13 +197,81 @@
test("Finding a file", function()
{
var zip = new JSZip();
- zip.add("Readme", "Hello World!\n");
- zip.add("Readme.French", "Bonjour tout le monde!\n");
- zip.add("Readme.Pirate", "Ahoy m'hearty!\n");
+ zip.file("Readme", "Hello World!\n");
+ zip.file("Readme.French", "Bonjour tout le monde!\n");
+ zip.file("Readme.Pirate", "Ahoy m'hearty!\n");
+
+ equals(zip.file("Readme.French").data, "Bonjour tout le monde!\n", "Exact match found");
+ equals(zip.file("Readme.Deutch"), null, "Match exactly nothing");
+ equals(zip.file(/Readme\../).length, 2, "Match regex free text");
+ equals(zip.file(/pirate/i).length, 1, "Match regex 1 result");
+ });
+
+ test("Finding a file : modifying the result doesn't alter the zip", function()
+ {
+ var expected = refZips["text"];
+
+ var zip = new JSZip();
+ zip.file("Hello.txt", "Hello World\n");
+ zip.file("Hello.txt").data = "new data";
+ zip.file("Hello.txt").name = "Hello2.txt";
+ zip.file("Hello.txt").options.dir = true;
+ // these changes won't be used
+ var content = zip.generate();
+
+ var actual = JSZipBase64.decode(content);
+
+ ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
+ });
+
+ test("Finding a file (text search) with a relative folder", function()
+ {
+ var zip = new JSZip();
+ zip.folder("files/default").file("Readme", "Hello World!\n");
+ zip.folder("files/translation").file("Readme.French", "Bonjour tout le monde!\n");
+ zip.folder("files").folder("translation").file("Readme.Pirate", "Ahoy m'hearty!\n");
+
+ equals(zip.file("files/translation/Readme.French").data, "Bonjour tout le monde!\n", "finding file with the full path");
+ equals(zip.folder("files").file("translation/Readme.French").data, "Bonjour tout le monde!\n", "finding file with a relative path");
+ equals(zip.folder("files/translation").file("Readme.French").data, "Bonjour tout le monde!\n", "finding file with a relative path");
+ });
+
+ test("Finding files (regex) with a relative folder", function()
+ {
+ var zip = new JSZip();
+ zip.folder("files/default").file("Readme", "Hello World!\n");
+ zip.folder("files/translation").file("Readme.French", "Bonjour tout le monde!\n");
+ zip.folder("files").folder("translation").file("Readme.Pirate", "Ahoy m'hearty!\n");
+
+ equals(zip.file(/Readme/).length, 3, "match files in subfolders");
+ equals(zip.folder("files/translation").file(/Readme/).length, 2, "regex match only in subfolders");
+ equals(zip.folder("files").folder("translation").file(/Readme/).length, 2, "regex match only in subfolders");
+ equals(zip.folder("files/translation").file(/pirate/i).length, 1, "regex match only in subfolders");
+ equals(zip.folder("files/translation").file(/^readme/i).length, 2, "regex match only with the relative path");
+ equals(zip.folder("files/default").file(/pirate/i).length, 0, "regex match only in subfolders");
+ });
+
+ test("Finding folders", function ()
+ {
+ var zip = new JSZip();
+ zip.folder("root/").folder("sub1/");
+ zip.folder("root/sub2/subsub1");
+
+ equals(zip.folder(/sub2\/$/).length, 1, "unique result");
+ equals(zip.folder(/sub1/).length, 2, "multiple results");
+ equals(zip.folder(/root/).length, 4, "match on whole path");
+ });
- ok(1 === zip.find("Readme").length, "Exact match found");
- ok(0 === zip.find("French").length, "Match exactly nothing");
- ok(2 === zip.find(/Readme\../).length, "Match regex free text");
+ test("Finding folders with relative path", function () {
+ var zip = new JSZip();
+ zip.folder("root/").folder("sub1/");
+ zip.folder("root/sub2/subsub1");
+ var root = zip.folder("root/sub2");
+
+ equals(root.folder(/sub2\/$/).length, 0, "current folder is not matched");
+ equals(root.folder(/sub1/).length, 1, "sub folder is matched");
+ equals(root.folder(/^subsub1/).length, 1, "relative folder path is used");
+ equals(root.folder(/root/).length, 0, "parent folder is not matched");
});
module("More advanced");
@@ -188,28 +281,57 @@
var expected = refZips["text"];
var zip = new JSZip();
- zip.add("Remove.txt", "This file should be deleted\n");
- zip.add("Hello.txt", "Hello World\n");
+ zip.file("Remove.txt", "This file should be deleted\n");
+ zip.file("Hello.txt", "Hello World\n");
zip.remove("Remove.txt");
- content = zip.generate();
+ var content = zip.generate();
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
+ test("Delete file in folder", function()
+ {
+ var expected = refZips["folder"];
+
+ var zip = new JSZip();
+ zip.folder("folder").file("Remove.txt", "This folder and file should be deleted\n");
+ zip.remove("folder/Remove.txt");
+ var content = zip.generate();
+
+ var actual = JSZipBase64.decode(content);
+
+ ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
+ });
+
+ test("Delete file in folder, with a relative path", function()
+ {
+ var expected = refZips["folder"];
+
+ var zip = new JSZip();
+ var folder = zip.folder("folder");
+ folder.file("Remove.txt", "This folder and file should be deleted\n");
+ folder.remove("Remove.txt");
+ var content = zip.generate();
+
+ var actual = JSZipBase64.decode(content);
+
+ ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
+ });
+
test("Delete folder", function()
{
var expected = refZips["text"];
var zip = new JSZip();
- zip.folder("remove").add("Remove.txt", "This folder and file should be deleted\n");
- zip.add("Hello.txt", "Hello World\n");
+ zip.folder("remove").file("Remove.txt", "This folder and file should be deleted\n");
+ zip.file("Hello.txt", "Hello World\n");
zip.remove("remove");
- content = zip.generate();
+ var content = zip.generate();
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
@@ -220,40 +342,124 @@
var expected = refZips["text"];
var zip = new JSZip();
- zip.folder("remove").add("Remove.txt", "This folder and file should be deleted\n");
- zip.folder("remove/second").add("Sub.txt", "This should be removed");
- zip.add("remove/second/another.txt", "Another file");
- zip.add("Hello.txt", "Hello World\n");
+ zip.folder("remove").file("Remove.txt", "This folder and file should be deleted\n");
+ zip.folder("remove/second").file("Sub.txt", "This should be removed");
+ zip.file("remove/second/another.txt", "Another file");
+ zip.file("Hello.txt", "Hello World\n");
zip.remove("remove");
- content = zip.generate();
+ var content = zip.generate();
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
+ test("Delete nested folders from relative path", function()
+ {
+ var expected = refZips["folder"];
+
+ var zip = new JSZip();
+ zip.folder("folder");
+ zip.folder("folder/1/2/3");
+ zip.folder("folder").remove("1");
+ var content = zip.generate();
+
+ var actual = JSZipBase64.decode(content);
+
+ ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
+ equals(reload(actual), actual, "Generated ZIP can be parsed");
+ });
+
test("Byte string output", function()
{
var expected = refZips["text"];
var zip = new JSZip();
- zip.add("Hello.txt", "Hello World\n");
- content = zip.generate(true);
+ zip.file("Hello.txt", "Hello World\n");
+ var content = zip.generate({base64:false});
var actual = content;
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
+ test("Filtering a zip", function()
+ {
+ var zip = new JSZip();
+ zip.file("1.txt", "1\n");
+ zip.file("2.txt", "2\n");
+ zip.file("3.log", "3\n");
+ var result = zip.filter(function (relativeFilename, file){
+ return relativeFilename.indexOf(".txt") != -1;
+ });
+ equals(result.length, 2, "filter has filtered");
+ ok(result[0].name.indexOf(".txt") != -1, "filter has filtered the good file");
+ ok(result[1].name.indexOf(".txt") != -1, "filter has filtered the good file");
+ });
+
+ test("Filtering a zip from a relative path", function()
+ {
+ var zip = new JSZip();
+ zip.file("foo/1.txt", "1\n");
+ zip.file("foo/2.txt", "2\n");
+ zip.file("foo/3.log", "3\n");
+ zip.file("1.txt", "1\n");
+ zip.file("2.txt", "2\n");
+ zip.file("3.log", "3\n");
+
+ var result = zip.folder("foo").filter(function (relativeFilename, file){
+ return relativeFilename.indexOf("3") != -1;
+ });
+ equals(result.length, 1, "filter has filtered");
+ equals(result[0].name, "foo/3.log", "filter has filtered the good file");
+ });
+
+ test("Filtering a zip : the full path is still accessible", function()
+ {
+ var zip = new JSZip();
+ zip.file("foo/1.txt", "1\n");
+ zip.file("foo/2.txt", "2\n");
+ zip.file("foo/3.log", "3\n");
+ zip.file("1.txt", "1\n");
+ zip.file("2.txt", "2\n");
+ zip.file("3.log", "3\n");
+
+ var result = zip.folder("foo").filter(function (relativeFilename, file){
+ return file.name.indexOf("3") != -1;
+ return file.name.indexOf("3") != -1 && file.name.indexOf("foo") != -1;
+ });
+ equals(result.length, 1, "the filter only match files/folders in the current folder");
+ equals(result[0].name, "foo/3.log", "filter has filtered the good file");
+ });
+
+ test("Filtering a zip : the filter function can't alter the data", function()
+ {
+ var expected = refZips["text"];
+
+ var zip = new JSZip();
+ zip.file("Hello.txt", "Hello World\n");
+ zip.filter(function (relativeFilename, file) {
+ file.name = "bye.txt";
+ file.data = "good bye";
+ file.options.dir = true;
+ });
+ var content = zip.generate();
+
+ var actual = JSZipBase64.decode(content);
+
+ ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
+
+ });
+
test("STORE is the default method", function()
{
var expected = refZips["text"];
- var zip = new JSZip("STORE");
- zip.add("Hello.txt", "Hello World\n");
- content = zip.generate();
+ var zip = new JSZip();
+ zip.file("Hello.txt", "Hello World\n");
+ var content = zip.generate({compression:'STORE'});
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
// no difference with the "Zip text file" test.
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
@@ -263,11 +469,11 @@
{
var expected = refZips["STORE-text"]; // zip -0 -X store.zip Hello.txt
- var zip = new JSZip("STORE");
- zip.add("Hello.txt", "This a looong file : we need to see the difference between the different compression methods.\n");
- content = zip.generate();
+ var zip = new JSZip();
+ zip.file("Hello.txt", "This a looong file : we need to see the difference between the different compression methods.\n");
+ var content = zip.generate({compression:'STORE'});
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
@@ -277,11 +483,11 @@
{
var expected = refZips["DEFLATE-text"]; // zip -6 -X deflate.zip Hello.txt
- var zip = new JSZip("DEFLATE");
- zip.add("Hello.txt", "This a looong file : we need to see the difference between the different compression methods.\n");
- content = zip.generate();
+ var zip = new JSZip();
+ zip.file("Hello.txt", "This a looong file : we need to see the difference between the different compression methods.\n");
+ var content = zip.generate({compression:'DEFLATE'});
- actual = JSZipBase64.decode(content);
+ var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
View
0 test/ref/utf8.zip 100755 → 100644
File mode changed.

0 comments on commit 773196f

Please sign in to comment.
Something went wrong with that request. Please try again.