-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostZip.js
89 lines (84 loc) · 3.14 KB
/
postZip.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
var fs = require("fs");
var path = require("path");
var url = require("url");
var http = require("http");
var https = require("https");
var JSZip = require("jszip");
var mkdirp = require("mkdirp");
function addFolder(folder, zip) {
if (!fs.existsSync(folder)) {
console.log("Error: postZIP - folder not found:", folder);
} else {
let files = fs.readdirSync(folder),
file, stat, sourcePath;
while (files.length > 0) {
file = files.shift();
sourcePath = path.join(folder, file);
stat = fs.statSync(sourcePath);
if (stat.isFile()) {
zip.file(file, fs.readFileSync(sourcePath), { binary: true });
} else {
addFolder(sourcePath + path.sep, zip.folder(file));
}
}
}
}
module.exports = function (_paths, fileName, output) {
let zip = new JSZip();
if (!Array.isArray(_paths)) {
_paths = [_paths];
}
// console.log(fileName, "paths:", _paths);
return new Promise(resolve => {
zip.file("blank.txt", "Blank generator");
for (let p of _paths) {
if (typeof p === "string") {
addFolder(p, zip);
} else {
let dest = zip;
if (p.folder) {
dest = zip.folder(p.folder);
}
if (p.file && p.data) {
var options;
if (typeof p.data !== "string") {
options = {
binary: true,
};
}
dest.file(p.file, p.data, options);
}
if (p.path) {
addFolder(p.path, dest);
}
}
}
if (output.indexOf("http") === 0) {
let postUrlString = output + "/" + fileName + "/" + fileName + ".zip";
let postUrl = url.parse(postUrlString);
let h = postUrl.protocol === "https:" ? https : http;
let req = h.request(Object.assign(postUrl, {
method: "POST",
}), (res) => {
console.log(`Post ${fileName} to service registry result: ${res.statusCode}/${res.statusMessage}`);
});
console.log("Generating zip archive...");
zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" }).then((content) => {
console.log(`Posting ${fileName} to service registry: "${postUrlString}"`);
req.write(content, "binary");
req.end();
});
return resolve();
}
output = path.resolve(output);
mkdirp.sync(output);
let outputFile = output + path.sep + fileName + ".zip";
console.log(`${new Date()} Writing ${fileName} to: ${outputFile}`);
zip.generateNodeStream({ type: "nodebuffer", streamFiles: true, compression: "DEFLATE" })
.pipe(fs.createWriteStream(outputFile))
.on("finish", function () {
console.log(`${new Date()} The ${fileName} was saved!`);
return resolve();
});
});
};