diff options
| author | Michael Williamson <mike@zwobble.org> | 2013-04-11 23:00:06 +0100 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2013-04-11 23:00:06 +0100 |
| commit | 90cf7be66b7ecbe11066fafcdcacf8f0c6bcf3e9 (patch) | |
| tree | 9f8d0f3e98f70982661589fcce2163eec39edbc3 /lib/unzip.js | |
| parent | 1d9da5d8ed67e3f31ebda8f12082e6e607c673f0 (diff) | |
Move unzip code into separate module
Diffstat (limited to 'lib/unzip.js')
| -rw-r--r-- | lib/unzip.js | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/lib/unzip.js b/lib/unzip.js new file mode 100644 index 0000000..858a4da --- /dev/null +++ b/lib/unzip.js @@ -0,0 +1,72 @@ +exports.unzipUint8Array = unzipUint8Array; +exports.unzipStream = unzipStream; + +var q = require("q"); +var unzip = { + Parse: require("unzip/lib/parse") +}; +var Buffers = require("buffers"); +var streamBuffers = require("stream-buffers"); + + +function unzipUint8Array(array) { + var buffer = new Buffer(array); + var stream = new streamBuffers.ReadableStreamBuffer(); + stream.put(buffer); + return unzipStream(stream); +} + +function unzipStream(stream) { + var deferred = q.defer(); + var names = []; + var files = {}; + + stream + .pipe(unzip.Parse()) + .on("entry", function(entry) { + names.push(entry.path); + files[entry.path] = readEntry(entry); + }) + .on("close", function() { + deferred.resolve(zipFile); + }) + .on("error", function(err) { + deferred.reject(err); + }); + + var exists = function(path) { + return names.indexOf(path) !== -1; + } + + function readEntry(entry) { + var readDeferred = q.defer(); + var buffers = new Buffers(); + + entry + .on("data", function(data) { + buffers.push(data); + }) + .on("end", function() { + readDeferred.resolve(buffers); + }) + .on("error", readDeferred.reject.bind(readDeferred)) + + return readDeferred.promise; + } + var zipFile = { + read: function(path, encoding) { + if (!exists(path)) { + return q.reject(new Error("No file in zip: " + path)); + } + return files[path].then(function(buffer) { + if (encoding) { + return buffer.toString(encoding); + } else { + return buffer; + } + }); + }, + exists: exists + }; + return deferred.promise; +} |
