task.js
3.3 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/* jshint esversion: 6 */
let fs = require('fs');
let path = require('path');
let endOfLine = require('os').EOL;
module.exports = {
maxHistoryNum: 5,
historyFile: path.resolve(__dirname, './dist/history.js'),
staticDir: path.resolve(__dirname, './dist/'),
/*
r 打开只读文件,该文件必须存在。
r+ 打开可读写的文件,该文件必须存在。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。
*/
creataHistoryIfNotExist () {
if (!fs.existsSync(this.historyFile)) {
this.storeHistory([], 'a+');
}
},
// @done 将数据写到 history.js
storeHistory (list, mode) {
let historyFile = this.historyFile;
let outJson = 'module.exports = [' + endOfLine;
let listLen = list.length;
if (list && listLen > 0) {
list.forEach((item, index) => {
if (index === listLen - 1) {
outJson += ` ${item}${endOfLine}`;
} else {
outJson += ` ${item},${endOfLine}`;
}
});
}
outJson += ']' + endOfLine;
fs.writeFileSync(historyFile, outJson, {
flag: mode
});
},
// 递归删除目录中的文件
rmFiles (dirPath, regexp) {
let files;
try {
files = fs.readdirSync(dirPath);
} catch (e) {
return;
}
if (regexp && files && files.length > 0) {
for (let i = 0; i < files.length; i++) {
let filename = files[i];
let filePath = dirPath + '/' + files[i];
if (fs.statSync(filePath).isFile() && regexp.test(filename)) {
console.warn('删除过期的历史版本->(' + regexp + '):' + filename);
fs.unlinkSync(filePath);
} else {
this.rmFiles(filePath, regexp);
}
}
}
},
// @done
cleanOldVersionFilesIfNeed (version) {
let staticDir = this.staticDir;
let maxHistoryNum = this.maxHistoryNum;
let history = [];
try {
history = require(this.historyFile);
} catch (e) {
console.error(e);
}
// 加入最新的版本,老的的版本删除
history.push(version);
// 如果历史版本数超过限制,则删除老的历史版本
let len = history.length;
if (len > maxHistoryNum) {
let oldVersions = history.slice(0, len - maxHistoryNum);
for (let i = 0; i < oldVersions.length; i++) {
let ver = oldVersions[i];
let reg = new RegExp(ver);
this.rmFiles(staticDir, reg);
}
// 更新history文件
let newVersions = history.slice(len - maxHistoryNum);
this.storeHistory(newVersions);
} else {
// 写入history文件
this.storeHistory(history);
}
},
// 入口
run (version) {
this.creataHistoryIfNotExist();
this.cleanOldVersionFilesIfNeed(version);
}
};