-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.js
More file actions
44 lines (37 loc) · 930 Bytes
/
cache.js
File metadata and controls
44 lines (37 loc) · 930 Bytes
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
const fs = require('fs');
const path = require('path');
const cacheFile = path.join(__dirname, './cacheData.json');
// 清除缓存
const clean = () => {
fs.writeFileSync(cacheFile, JSON.stringify([]));
};
// 读取缓存
const get = () => {
if (fs.existsSync(cacheFile)) {
const cacheData = fs.readFileSync(cacheFile, 'utf8');
try {
return JSON.parse(cacheData || '[]');
} catch (err) {
// 出错后,重置缓存文件数据
clean();
return [];
}
}
return [];
};
// 写入缓存
const write = (value) => {
const cacheData = get();
const nextCacheData = [...(cacheData || []), value].filter(Boolean);
const str = JSON.stringify(nextCacheData);
fs.writeFile(cacheFile, str, (err) => {
if (err) {
console.error(err);
}
});
};
module.exports = {
get,
write,
clean,
};