UNPKG

1.23 kBJavaScriptView Raw
1const fse = require('fs-extra');
2
3const underPath = require('./underPath');
4
5const {
6 jsonStringify,
7} = require('./jsonOp');
8
9const defaultDir = underPath('root'); // 默认 .cache 目录位于项目根目录下
10
11class Cache {
12 constructor(dir = defaultDir) {
13 this.cacheDir = underPath(dir, '.cache');
14 }
15
16 /**
17 * 保存信息
18 */
19 save(filename, info) {
20 fse.outputFileSync(this.getFilePath(filename), `${jsonStringify(info)}\n`);
21 }
22
23 /**
24 * 移除信息
25 */
26 remove(filename) {
27 fse.removeSync(this.getFilePath(filename));
28 }
29
30 /**
31 * 是否有缓存
32 */
33 has(filename) {
34 fse.pathExistsSync(this.getFilePath(filename));
35 }
36
37 /**
38 * 获取信息
39 */
40 get(filename) {
41 const filePath = this.getFilePath(filename);
42 if (fse.pathExistsSync(filePath)) {
43 return fse.readJsonSync(filePath);
44 }
45 return null;
46 }
47
48 /**
49 * 清空所有缓存
50 */
51 cleanAll() {
52 fse.removeSync(this.cacheDir);
53 }
54
55 /**
56 * 获取缓存文件的路径
57 */
58 getFilePath(filename) {
59 const realname = filename.includes('.') ? filename : `${filename}.json`; // 未指定文件格式时默认 json
60 return underPath(this.cacheDir, realname);
61 }
62}
63
64module.exports = Cache;