aboutsummaryrefslogtreecommitdiff
path: root/node_modules/express-minify/cache.js
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/express-minify/cache.js')
-rw-r--r--node_modules/express-minify/cache.js71
1 files changed, 71 insertions, 0 deletions
diff --git a/node_modules/express-minify/cache.js b/node_modules/express-minify/cache.js
new file mode 100644
index 0000000..95dff37
--- /dev/null
+++ b/node_modules/express-minify/cache.js
@@ -0,0 +1,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;