JSZip 简单使用

JSZip 是一个用于创建、读取和编辑.zip文件的JavaScript库,且API的使用也很简单。如下是使用 JSZip 压缩一个文件夹到指定目录的例子。

zip.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
let fs = require('fs');
let path = require('path');
let JsZip = require('jszip');
let zip = new JsZip();
// 读取目录及文件
function readDir(obj, nowPath, nowFolder) {
// 读取目录中的所有文件及文件夹
let files = fs.readdirSync(nowPath);
files.forEach(function (fileName, index) {
// 遍历检测目录中的文件
let fillPath = nowPath + '/' + fileName;
let file = fs.statSync(fillPath);
if (file.isDirectory()) {
// 如果是目录的话,继续查询
let folder = nowFolder + '/' + fileName;
// 压缩对象中生成该目录
let dirList = zip.folder(folder);
// 重新检索目录文件
readDir(dirList, fillPath, folder);
} else {
// 如果是文件压缩目录添加文件
obj.file(fileName, fs.readFileSync(fillPath));
}
});
}
// 开始压缩文件
function startZIP() {
var currPath = __dirname;
// 要压缩的文件夹目录
var sourceDir = path.join(currPath, '../../dist:source/');
// 生成压缩包的目录
var targetDir = path.join(currPath, '../../dist:app/static/source.zip');
readDir(zip, sourceDir, '');
zip
.generateAsync({
type: 'nodebuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 9,
},
})
.then(function (content) {
fs.writeFileSync(targetDir, content, 'utf-8');
console.log('压缩完成');
});
}
startZIP();

命令:

1
node zip.js