-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcache.js
100 lines (81 loc) · 2.25 KB
/
cache.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
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
const fs = require('fs');
const path = require('path');
// 获取调用文件的文件名
function getCallerFileName() {
const originalFunc = Error.prepareStackTrace;
let callerfile;
try {
const err = new Error();
let currentfile;
Error.prepareStackTrace = (err, stack) => stack;
currentfile = err.stack.shift().getFileName();
while (err.stack.length) {
callerfile = err.stack.shift().getFileName();
if (currentfile !== callerfile) break;
}
} catch (e) {}
Error.prepareStackTrace = originalFunc;
return path.basename(callerfile, '.js');
}
// 获取缓存文件路径
function getCacheFilePath() {
const callerFileName = getCallerFileName();
return path.join(__dirname, `${callerFileName}_cache.json`);
}
// 初始化缓存文件
function initializeCache() {
const cacheFilePath = getCacheFilePath();
if (!fs.existsSync(cacheFilePath)) {
fs.writeFileSync(cacheFilePath, JSON.stringify({}));
}
}
// 读取缓存文件
function readCache(key) {
const cacheFilePath = getCacheFilePath();
const data = fs.readFileSync(cacheFilePath, 'utf-8');
return JSON.parse(data)[key];
}
// 写入缓存文件
function writeCache(data) {
const cacheFilePath = getCacheFilePath();
fs.writeFileSync(cacheFilePath, JSON.stringify(data, null, 2));
}
// 新增缓存
function addCache(key, value) {
const cacheFilePath = getCacheFilePath();
let cache = {};
if (fs.existsSync(cacheFilePath)) {
const data = fs.readFileSync(cacheFilePath, 'utf-8');
cache = JSON.parse(data);
}
cache[key] = value;
writeCache(cache);
}
// 修改缓存
function updateCache(key, value) {
const cache = readCache();
if (cache.hasOwnProperty(key)) {
cache[key] = value;
writeCache(cache);
} else {
console.log(`Key "${key}" does not exist.`);
}
}
// 删除缓存
function deleteCache(key) {
const cache = readCache();
if (cache.hasOwnProperty(key)) {
delete cache[key];
writeCache(cache);
} else {
console.log(`Key "${key}" does not exist.`);
}
}
// 导出模块
module.exports = {
initializeCache,
addCache,
updateCache,
deleteCache,
readCache
};