UNPKG

2.46 kBJavaScriptView Raw
1const fs = require('fs-extra'),
2 path = require('path'),
3 pathInfo = require('./getPathInfo'),
4 archiver = require('archiver');
5
6module.exports = (filePath,outPath)=>{
7 return new Promise((resolve,reject)=>{
8 //输入的路径无效则抛出错误
9 if(!fs.existsSync(filePath)){
10 reject({
11 status:'success',
12 msg:`${filePath} 不是有效的路径`
13 });
14 };
15
16 //确保输出目录已经存在
17 let outDir = path.dirname(outPath);
18 fs.ensureDir(outDir);
19
20 let output = fs.createWriteStream(outPath), //压缩包文件流
21 zipDirName = path.basename(outPath,path.extname(outPath)), //压缩包内目录名
22 archive = archiver('tar',{
23 zlib:{
24 level:9
25 }
26 });
27
28 //完成捕获
29 archive.on('end',() => {
30 resolve({
31 status:'success',
32 msg:`${filePath} 压缩成功`
33 });
34 });
35
36 //错误捕获
37 archive.on('error',err => {
38 reject({
39 status:'error',
40 msg:`${filePath} 压缩遇到错误`,
41 data:err
42 });
43 });
44
45 archive.pipe(output);
46 // archive.directory(filePath,zipDirName);
47
48 let files = fs.readdirSync(filePath);
49 files.forEach(item => {
50 let itemPath = path.join(filePath,item),
51 itemInfo = pathInfo(itemPath),
52 isIgnore = (()=>{
53 // 过滤掉所有以'.'开头的文件及目录及'node_modules'目录
54 if(item[0] === '.' || item === 'node_modules'){
55 return true;
56 };
57
58 // 过滤掉以下文件类型
59 return ['tar','zip','rar'].some(item => {
60 return '.'+item === itemInfo.extension;
61 });
62 })();
63
64 // 如果不是需要过滤的文件则添加到压缩包
65 if(!isIgnore){
66 if(itemInfo.type === 'file'){
67 archive.file(itemPath,{name:zipDirName + '/' + item});
68 }else{
69 archive.directory(itemPath,zipDirName + '/' + item);
70 };
71 };
72
73 });
74 archive.finalize();
75 });
76};
\No newline at end of file