-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
57 lines (52 loc) · 1.36 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
import fs from 'fs/promises';
let dir = './.cache/';
async function createCacheDir() {
try {
await fs.mkdir(dir, { recursive: true });
} catch (err) {
throw new Error('Couldn\'t create .cache directory.');
}
}
async function cacheJSON(fileName, obj) {
try {
let file = dir + fileName + '.json';
obj = JSON.stringify(obj, null, 2);
await fs.writeFile(file, obj);
} catch (err) {
throw new Error('Couldn\'t cache ' + fileName);
}
}
async function readCache(fileName) {
let file = dir + fileName + '.json';
try {
await fs.access(file);
let obj = await fs.readFile(file, { encoding: 'utf-8' });
if (obj !== '') {
try {
obj = JSON.parse(obj);
return obj;
} catch (err) {
console.log('In "' + file + '" format not json.');
let newFile = dir + fileName + '.wrong_format';
console.log('Contents moved to ' + newFile);
await fs.writeFile(newFile, obj);
await fs.writeFile(file, '');
}
}
return null;
} catch (err) {
if (err.code === 'ENOENT') {
console.log('No cache for ', file);
console.log('Creating cahce file ' + file + '...');
await fs.writeFile(file, '');
return null;
} else {
Promise.reject(err);
}
}
}
export default {
createCacheDir: createCacheDir,
cacheJSON: cacheJSON,
readCache: readCache,
}