blob: ea6f710290bc429bdd658dcb5bde2d9f62661025 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
exports.openZip = openZip;
var promises = require("./promises");
var fs = require("fs");
var unzip = {
Parse: require("unzip/lib/parse")
};
var Buffers = require("buffers");
var streamBuffers = require("stream-buffers");
function openZip(options) {
if (options.path) {
return unzipStream(fs.createReadStream(options.path));
} else if (options.file) {
return options.file;
} else {
return promises.reject(new Error("Could not find file in options"));
}
}
function unzipStream(stream) {
var deferred = promises.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 = promises.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 promises.reject(new Error("No file in zip: " + path));
}
return files[path].then(function(buffer) {
if (encoding) {
return buffer.toString(encoding);
} else {
return buffer.toBuffer();
}
});
},
exists: exists
};
return deferred.promise;
}
|