ZipUtils.js
1.64 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
import fs from "fs-extra";
import archiver from "archiver";
import unzip from "unzip-stream";
class ZipUtils {
/**
* @description ZipUtils.zip('/xx/floder',floder,'/output/','myzip.zip')
* @param {String} sourcePath
* @param {String} fromFloderName
* @param {String} destinationFolder
* @param {String} zipFileName
* @returns {String}
*/
static async zip(sourcePath,fromFloderName, destinationFolder, zipFileName) {
let zipFilePath = destinationFolder + zipFileName;
fs.ensureDirSync(destinationFolder);
const archive = archiver("zip");
const outputSteam = fs.createWriteStream(zipFilePath);
await archive.pipe(outputSteam);
await archive.directory(sourcePath,fromFloderName );
await archive.finalize();
return zipFilePath;
}
/**
* @description ZipUtils.unzip("/tmp/myzip.zip",/tmp/output)
* @param {String} zipFilePath
* @param {String} extractToPath
*/
static async unzip(zipFilePath,extractToPath){
//fs.ensureFileSync(extractToPath);
await new Promise((subResolve, subReject) => {
fs.createReadStream(zipFilePath)
.pipe(unzip.Extract({
path: extractToPath
}))
.on("close", async function (entry) {
console.log('extract file successfully');
subResolve(entry);
})
.on("error", async function (error) {
console.log('extract file failed');
subReject(error);
});
});
return extractToPath;
}
}
export default ZipUtils;