-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunzip.js
More file actions
62 lines (50 loc) · 2.26 KB
/
Copy pathunzip.js
File metadata and controls
62 lines (50 loc) · 2.26 KB
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
const fs = require('fs');
const StreamZip = require('node-stream-zip');
module.exports = {
unzipArchive: async (pathToDirectory, file) => {
//replace the extension of the file to .zip
const pos = file.lastIndexOf(".");
const fileRevised = file.substr(0, pos < 0 ? file.length : pos) + ".zip";
//Rename the file on disk
return new Promise((resolve, reject) => {
const entryNames = [];
fs.rename(`${pathToDirectory}/${file}`, `${pathToDirectory}/${fileRevised}`, function (err) {
//handle error when renaming
if (err) reject('ERROR: ' + err);
//Open a zip file
const zip = new StreamZip({
file: `${pathToDirectory}/${fileRevised}`,
storeEntries: true
});
// Handle errors while dealing with zip file
zip.on('error', err => {
console.error('something went wrong', err);
});
//Store the entries and file names for the sorting stage
zip.on('extract', (entry, file) => {
if(entry) {
entryNames.push({entry: entry.name, file});
}
});
// extract everything in the archive to a directory named extracted
zip.on('ready', () => {
fs.mkdirSync(`${pathToDirectory}/${file}`);
zip.extract(null, `${pathToDirectory}/${file}`, (err, count) => {
if (err) {
reject({
message: 'Extract error',
status: false
})
}
zip.close();
resolve({
message: `Extracted entries`,
status: true,
entries: entryNames
})
});
});
});
});
}
};