1 | const fs = require('fs-extra'),
|
2 | path = require('path'),
|
3 | pathInfo = require('./getPathInfo'),
|
4 | archiver = require('archiver');
|
5 |
|
6 | module.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 |
|
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 |
|
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 |