-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive.js
74 lines (71 loc) · 2.23 KB
/
archive.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
const fs = require('fs')
const path = require('path')
const yauzl = require('yauzl')
function unzip(pn, altTopFolder, verbose) {
let topFolder = undefined;
let nFiles = 0;
let nFolders = 0;
yauzl.open(pn, {lazyEntries: true}, function(err, zipfile) {
if (err) {
console.log(err.message);
process.exit(1);
}
zipfile.readEntry();
zipfile.on("end", function() {
console.log(`Unzipped ${nFolders} folders, ${nFiles} files to '${altTopFolder}'.`)
});
zipfile.on("entry", function(entry) {
if (/\/$/.test(entry.fileName)) {
let folderToCreate;
// First test to see if this is the first folder, and if specified, store that
if (altTopFolder && !topFolder) {
topFolder = entry.fileName;
}
// Directory file names end with '/'.
// Note that entries for directories themselves are optional.
// An entry's fileName implicitly requires its parent directories to exist.
if (entry.fileName.startsWith(topFolder)) {
folderToCreate = path.join(altTopFolder, entry.fileName.slice(topFolder.length));
} else {
folderToCreate = entry.fileName;
}
if (verbose) {
console.log(folderToCreate);
}
try {
fs.mkdirSync(folderToCreate);
nFolders++;
}
catch (err) {
console.error(`Unzip error: `+err.message);
process.exit(1);
}
zipfile.readEntry();
} else {
// file entry
let fileToCreate;
if (topFolder && entry.fileName.startsWith(topFolder)) {
fileToCreate = path.join(altTopFolder, entry.fileName.slice(topFolder.length));
} else {
fileToCreate = entry.fileName;
}
if (verbose) {
console.log(fileToCreate);
}
const writer = fs.createWriteStream(fileToCreate)
zipfile.openReadStream(entry, function(err, readStream) {
if (err) {
console.log(err.message);
process.exit(1);
}
readStream.on("end", function() {
nFiles++;
zipfile.readEntry();
});
readStream.pipe(writer);
});
}
});
});
}
module.exports = { unzip }