1 | const fse = require('fs-extra');
|
2 |
|
3 | const underPath = require('./underPath');
|
4 |
|
5 | const {
|
6 | jsonStringify,
|
7 | } = require('./jsonOp');
|
8 |
|
9 | const defaultDir = underPath('root');
|
10 |
|
11 | class 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`;
|
60 | return underPath(this.cacheDir, realname);
|
61 | }
|
62 | }
|
63 |
|
64 | module.exports = Cache;
|