UNPKG

1.25 kBJavaScriptView Raw
1(function() {
2 var Cache, crypto, csVer, fs, ltVer, path;
3
4 fs = require('fs');
5
6 path = require('path');
7
8 crypto = require('crypto');
9
10 ltVer = require('./../package.json').version;
11
12 csVer = ((typeof window !== "undefined" && window !== null ? window.CoffeeScript : void 0) || require('coffeescript')).VERSION;
13
14 module.exports = Cache = class Cache {
15 constructor(basepath) {
16 this.basepath = basepath;
17 if (!fs.existsSync(this.basepath)) {
18 fs.mkdirSync(this.basepath, 0o755);
19 }
20 }
21
22 path(source) {
23 return path.join(this.basepath, `${csVer}-${ltVer}-${this.prefix}-${this.hash(source)}`);
24 }
25
26 get(source) {
27 return JSON.parse(fs.readFileSync(this.path(source), 'utf8'));
28 }
29
30 set(source, result) {
31 return fs.writeFileSync(this.path(source), JSON.stringify(result));
32 }
33
34 has(source) {
35 return fs.existsSync(this.path(source));
36 }
37
38 hash(data) {
39 return crypto.createHash('md5').update('' + data).digest('hex').substring(0, 8);
40 }
41
42 // Use user config as a "namespace" so that
43 // when he/she changes it the cache becomes invalid
44 setConfig(config) {
45 return this.prefix = this.hash(JSON.stringify(config));
46 }
47
48 };
49
50}).call(this);