-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
116 lines (102 loc) · 2.8 KB
/
index.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
var fs = require('fs');
var path = require('path');
var asyncLib = require('async');
var Zip = require('jszip');
// Limiting the number of files read at the same time
var maxOpenFiles = 500;
module.exports = function zipWrite (rootDir, options, callback) {
var promise, succeed, fail;
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
if (!callback) {
promise = new Promise(function (resolve, reject) {
succeed = resolve;
fail = reject;
});
}
zipBuffer(rootDir, options, function (err, buffer) {
if (!err && options.saveTo) {
fs.writeFile(options.saveTo, buffer, { encoding: 'binary' }, function (err) {
finish(err);
});
} else {
finish(err);
}
function finish (err) {
if (callback) {
callback(err, buffer);
} else {
if (err) {
fail(err);
} else {
succeed(buffer);
}
}
}
});
return promise;
};
function zipBuffer (rootDir, options, callback) {
var zip = new Zip();
var folders = {};
// Resolve the path so we can remove trailing slash if provided
rootDir = path.resolve(rootDir);
folders[rootDir] = zip;
dive(rootDir, function (err) {
if (err) return callback(err);
zip.generateAsync({
compression: 'DEFLATE',
type: 'nodebuffer'
}).then(function (buffer) {
callback(null, buffer);
}).catch(function (error) {
callback(error);
});
});
function dive (dir, callback) {
fs.readdir(dir, function (err, files) {
if (err) return callback(err);
if (!files.length) return callback();
var count = files.length;
files.forEach(function (file) {
var fullPath = path.resolve(dir, file);
addItem(fullPath, function (err) {
if (!--count) {
callback(err);
}
});
});
});
}
var fileQueue = asyncLib.queue(function (task, callback) {
fs.readFile(task.fullPath, function (err, data) {
if (options.each) {
options.each(path.join(task.dir, task.file));
}
folders[task.dir].file(task.file, data);
callback(err);
});
}, maxOpenFiles);
function addItem (fullPath, cb) {
fs.stat(fullPath, function (err, stat) {
if (err) return cb(err);
if (options.filter && !options.filter(fullPath, stat)) return cb();
var dir = path.dirname(fullPath);
var file = path.basename(fullPath);
var parentZip;
if (stat.isDirectory()) {
parentZip = folders[dir];
if (options.each) {
options.each(fullPath);
}
folders[fullPath] = parentZip.folder(file);
dive(fullPath, cb);
} else {
fileQueue.push({ fullPath: fullPath, dir: dir, file: file }, cb);
}
});
}
}