-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdn.js
More file actions
61 lines (53 loc) · 1.62 KB
/
cdn.js
File metadata and controls
61 lines (53 loc) · 1.62 KB
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
"use strict";
const fs = require('fs');
const path = require('path');
class CDN {
constructor(options = {}) {
this.dir = options.dir || './cdn/';
this.extension = options.extension || '.cdn.json';
this.ttl = (typeof options.ttl === 'number') ? options.ttl : 3600;
};
getFilePath(name) {
return path.resolve(path.join(this.dir, String(name).replace(/[^a-z0-9]+/gi, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') + this.extension));
};
cache(name, object) {
try {
const json = JSON.stringify(object);
const file = this.getFilePath(name);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, json);
return true;
} catch (e) {
console.error(e);
return false;
};
};
delete(name) {
try {
const file = this.getFilePath(name);
if (fs.existsSync(file)) fs.unlinkSync(file);
return true;
} catch (e) {
return false;
};
};
get(name) {
try {
return JSON.parse(fs.readFileSync(this.getFilePath(name), 'utf8'));
} catch (e) {
return false;
};
};
valid(name, ttl) {
ttl = (typeof ttl === 'number') ? ttl : this.ttl;
try {
const file = this.getFilePath(name);
if (!fs.existsSync(file)) return false;
const stats = fs.statSync(file);
return (stats.mtimeMs + ttl * 1000) > Date.now();
} catch (e) {
return false;
};
};
};
module.exports = CDN;