aboutsummaryrefslogtreecommitdiff
path: root/node_modules/express-minify/cache.js
blob: 95dff37debbb88fcbabef953f5da30aac155b65d (plain)
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
62
63
64
65
66
67
68
69
70
71
var fs = require('fs');
var path = require('path');

var FileCache = function (basePath) {
  this.basePath = basePath;
};

FileCache.prototype.get = function (hash, callback) {
  var destPath = this.basePath + hash;
  fs.readFile(destPath, {encoding: 'utf8'}, function (err, data) {
    if (err) {
      callback(err);
      return;
    }
    callback(null, data.toString());
  });
};

FileCache.prototype.put = function (hash, minized, callback) {
  var destPath = this.basePath + hash;
  var tempPath = destPath + '.tmp';
  // fix issue #3
  fs.writeFile(tempPath, minized, {encoding: 'utf8'}, function (err) {
    if (err) {
      callback(err);
      return;
    }
    fs.rename(tempPath, destPath, callback);
  });
};

var MemoryCache = function () {
  this.cache = {};
};

MemoryCache.prototype.get = function (hash, callback) {
  if (!this.cache.hasOwnProperty(hash)) {
    callback(new Error('miss'));
  } else {
    callback(null, this.cache[hash]);
  }
};

MemoryCache.prototype.put = function (hash, minized, callback) {
  this.cache[hash] = minized;
  callback();
};

/**
 * @param {String|false} cacheDirectory  false == use memory cache
 */
var Cache = function (cacheDirectory) {
  this.isFileCache = (cacheDirectory !== false);
  if (this.isFileCache) {
    // whether the directory is writeable
    cacheDirectory = path.normalize(cacheDirectory + '/').toString();
    try {
      fs.accessSync(cacheDirectory, fs.W_OK);
    } catch (ignore) {
      console.log('WARNING: express-minify cache directory is not writeable, fallback to memory cache.');
      this.isFileCache = false;
    }
  }
  if (this.isFileCache) {
    this.layer = new FileCache(cacheDirectory);
  } else {
    this.layer = new MemoryCache();
  }
};

module.exports = Cache;