Skip to content

Commit

Permalink
Merge pull request #275 from dduponchel/blob
Browse files Browse the repository at this point in the history
[JSZip v3] Blob, Promise and more.
  • Loading branch information
dduponchel committed Apr 11, 2016
2 parents 053d8d5 + 5b06e87 commit cb28f5e
Show file tree
Hide file tree
Showing 32 changed files with 606 additions and 239 deletions.
1 change: 0 additions & 1 deletion .jshintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
node_modules
test
7 changes: 7 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
{
"curly": true,
"eqeqeq": true,
"nonew": true,
"noarg": true,
"forin": true,
"futurehostile": true,
"freeze": true,
"undef": true,
"strict": true,
"sub": true,
Expand Down
26 changes: 21 additions & 5 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,27 @@ module.exports = function(grunt) {
}
},
jshint: {
options: {
jshintrc: "./.jshintrc"
},
all: ['./lib/**/*.js', './test/helpers/**/*.js', './test/asserts/**/*.js']
},
// see https://github.com/gruntjs/grunt-contrib-jshint/issues/198
// we can't override the options using the jshintrc path
options: grunt.file.readJSON('.jshintrc'),
production: ['./lib/**/*.js'],
test: ['./test/helpers/**/*.js', './test/asserts/**/*.js'],
documentation: {
options: {
globals: {
jQuery: false,
JSZip: false,
JSZipUtils: false,
saveAs: false
},
// implied still give false positives in our case
strict: false
},
files: {
src: ['./documentation/**/*.js']
}
}
},
browserify: {
all: {
files: {
Expand Down
14 changes: 12 additions & 2 deletions documentation/api_jszip/external.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,17 @@ section: api

JSZip uses polyfills of objects that may not exist on every platform.
Accessing or replacing these objects can sometimes be useful. JSZip.external
It contains the following properties :
contains the following properties :

* `Promise` : the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) used.
* `Promise` : the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) implementation used.

__Example__

```js
// use bluebird instead
JSZip.external.Promise = Bluebird;

// use the native Promise object:
JSZip.external.Promise = Promise;
```

5 changes: 3 additions & 2 deletions documentation/api_jszip/file_data.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ __Arguments__
name | type | description
--------------------|---------|------------
name | string | the name of the file. You can specify folders in the name : the folder separator is a forward slash ("/").
data | String/ArrayBuffer/Uint8Array/Buffer | the content of the file.
data | String/ArrayBuffer/Uint8Array/Buffer/Blob/Promise | the content of the file.
options | object | the options.

Content of `options` :
Expand Down Expand Up @@ -51,7 +51,8 @@ as a folder and the content will be ignored.

__Returns__ : The current JSZip object, for chaining.

__Throws__ : An exception if the data is not in a supported format.
__Throws__ : Nothing. (an exception will be propagated if the data is not in
a supported format).

<!--
__Complexity__ : **O(1)** for anything but binary strings.
Expand Down
2 changes: 1 addition & 1 deletion documentation/api_jszip/load_async.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ __Arguments__

name | type | description
-------------------|--------|------------
data | String/Array of bytes/ArrayBuffer/Uint8Array/Buffer | the zip file
data | String/Array of bytes/ArrayBuffer/Uint8Array/Buffer/Blob/Promise | the zip file
options | object | the options to load the zip file

Content of `options` :
Expand Down
2 changes: 1 addition & 1 deletion documentation/api_zipobject/async.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ __Arguments__

name | type | description
---------|----------|------------
type | String | the type of the result : `string` (or `text`, its alias), `binarystring`, `base64`, `uint8array`, `arraybuffer`, `nodebuffer`.
type | String | the type of the result : `string` (or `text`, its alias), `binarystring`, `base64`, `array`, `uint8array`, `arraybuffer`, `nodebuffer`.
onUpdate | Function | an optional function called on each internal update with the metadata.

__Metadata__ : the metadata are :
Expand Down
68 changes: 32 additions & 36 deletions documentation/examples/downloader.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
jQuery(function ($) {
"use strict";

var Promise = window.Promise;
if (!Promise) {
Promise = JSZip.external.Promise;
}

/**
* Reset the message.
*/
Expand Down Expand Up @@ -43,24 +48,20 @@ jQuery(function ($) {
}

/**
* Fetch the content, add it to the JSZip object
* and use a jQuery deferred to hold the result.
* Fetch the content and return the associated promise.
* @param {String} url the url of the content to fetch.
* @param {String} filename the filename to use in the JSZip object.
* @param {JSZip} zip the JSZip instance.
* @return {jQuery.Deferred} the deferred containing the data.
* @return {Promise} the promise containing the data.
*/
function deferredAddZip(url, filename, zip) {
var deferred = $.Deferred();
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
deferred.reject(err);
} else {
zip.file(filename, data, {binary:true});
deferred.resolve(data);
}
function urlToPromise(url) {
return new Promise(function(resolve, reject) {
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
reject(err);
} else {
resolve(data);
}
});
});
return deferred;
}

if(!JSZip.support.blob) {
Expand All @@ -73,39 +74,34 @@ jQuery(function ($) {
resetMessage();

var zip = new JSZip();
var deferreds = [];

// find every checked item
$(this).find(":checked").each(function () {
var $this = $(this);
var url = $this.data("url");
var filename = url.replace(/.*\//g, "");
deferreds.push(deferredAddZip(url, filename, zip));
zip.file(filename, urlToPromise(url), {binary:true});
});

// when everything has been downloaded, we can trigger the dl
$.when.apply($, deferreds).done(function () {
zip.generateAsync({type:"blob"}, function updateCallback(metadata) {
var msg = "progression : " + metadata.percent.toFixed(2) + " %";
if(metadata.currentFile) {
msg += ", current file = " + metadata.currentFile;
}
showMessage(msg);
updatePercent(metadata.percent|0);
})
.then(function callback( blob) {
zip.generateAsync({type:"blob"}, function updateCallback(metadata) {
var msg = "progression : " + metadata.percent.toFixed(2) + " %";
if(metadata.currentFile) {
msg += ", current file = " + metadata.currentFile;
}
showMessage(msg);
updatePercent(metadata.percent|0);
})
.then(function callback(blob) {

// see FileSaver.js
saveAs(blob, "example.zip");
// see FileSaver.js
saveAs(blob, "example.zip");

showMessage("done !");
}, function (e) {
showError(e);
});

}).fail(function (err) {
showError(err);
showMessage("done !");
}, function (e) {
showError(e);
});

return false;
});
});
Expand Down
37 changes: 34 additions & 3 deletions documentation/examples/get-binary-files-ajax.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,18 @@
<h3>With JSZipUtils</h3>
<div id="jszip_utils"></div>

<h3>With the Fetch API</h3>
<div id="fetch"></div>

<script type="text/javascript">
(function () {

function showError(elt, err) {
elt.innerHTML = "<p class='alert alert-danger'>" + err + "</p>";
}

function showContent(elt, type, content) {
elt.innerHTML = "<p class='alert alert-success'>loaded ! (as a " + type + ")<br/>" +
function showContent(elt, content) {
elt.innerHTML = "<p class='alert alert-success'>loaded !<br/>" +
"Content = " + content + "</p>";
}

Expand All @@ -37,7 +40,7 @@ <h3>With JSZipUtils</h3>
return zip.file("Hello.txt").async("string");
})
.then(function success(text) {
showContent(elt, "" + data, text);
showContent(elt, text);
}, function error(e) {
showError(elt, e);
});
Expand All @@ -46,5 +49,33 @@ <h3>With JSZipUtils</h3>
}
});

//=========================
// Fetch API
//=========================
(function () {
var elt = document.getElementById('fetch');
if(typeof window.fetch === "function") {
fetch('{{site.baseurl}}/test/ref/text.zip')
.then(function (response) {
if (response.status === 200 || response.status === 0) {
return Promise.resolve(response.arrayBuffer())
} else {
return Promise.reject(new Error(response.statusText))
}
})
.then(JSZip.loadAsync)
.then(function (zip) {
return zip.file("Hello.txt").async("string");
})
.then(function success(text) {
showContent(elt, text);
}, function error(e) {
showError(elt, e);
});
} else {
showError(elt, "This browser doesn't support the Fetch API.");
}
})();

})();
</script>
78 changes: 31 additions & 47 deletions documentation/examples/read-local-file-api.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,56 +32,40 @@ <h3>Content :</h3>
// be sure to show the results
$("#result_block").removeClass("hidden").addClass("show");

// see http://www.html5rocks.com/en/tutorials/file/dndfiles/
// Closure to capture the file information.
function handleFile(f) {
var $title = $("<h4>", {
text : f.name
});
var $fileContent = $("<ul>");
$result.append($title);
$result.append($fileContent);

var dateBefore = new Date();
JSZip.loadAsync(f)
.then(function(zip) {
var dateAfter = new Date();
$title.append($("<span>", {
text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
}));

var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {

var reader = new FileReader();

// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var $title = $("<h4>", {
text : theFile.name
});
$result.append($title);
var $fileContent = $("<ul>");
try {

var dateBefore = new Date();
// read the content of the file with JSZip
JSZip.loadAsync(e.target.result)
.then(function(zip) {
var dateAfter = new Date();

$title.append($("<span>", {
text:" (parsed in " + (dateAfter - dateBefore) + "ms)"
}));

zip.forEach(function (relativePath, zipEntry) {
$fileContent.append($("<li>", {
text : zipEntry.name
}));
// the content is here : zipEntry.async("string")
});
});
// end of the magic !

} catch(e) {
$fileContent = $("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + theFile.name + " : " + e.message
});
}
$result.append($fileContent);
}
})(f);
zip.forEach(function (relativePath, zipEntry) {
$fileContent.append($("<li>", {
text : zipEntry.name
}));
});
}, function (e) {
$fileContent = $("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + f.name + " : " + e.message
});
});
}

// read the file !
// readAsArrayBuffer and readAsBinaryString both produce valid content for JSZip.
reader.readAsArrayBuffer(f);
// reader.readAsBinaryString(f);
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
handleFile(f);
}
});
})();
Expand Down
16 changes: 7 additions & 9 deletions documentation/howto/read_zip.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,12 @@ var req = http.get(url.parse("http://localhost/.../file.zip"), function (res) {
});

res.on("end", function () {
var buf = new Buffer(dataLen);
for (var i=0,len=data.length,pos=0; i<len; i++) {
data[i].copy(buf, pos);
pos += data[i].length;
}
var buf = Buffer.concat(data);

// here we go !
var zip = new JSZip(buf);
zip.file("content.txt").async("string").then(function (text) {
JSZip.loadAsync(buf).then(function (zip) {
return zip.file("content.txt").async("string");
}).then(function (text) {
console.log(text);
});
});
Expand Down Expand Up @@ -148,8 +145,9 @@ request({
// handle error
return;
}
var zip = new JSZip(body);
zip.file("content.txt").async("string").then(function (text) {
JSZip.loadAsync(body).then(function (zip) {
return zip.file("content.txt").async("string");
}).then(function () {
console.log(text);
});
});
Expand Down
Loading

0 comments on commit cb28f5e

Please sign in to comment.