diff options
| author | nanalelfe <nargiza.nosirova@mail.utoronto.ca> | 2016-07-27 00:03:35 +0000 |
|---|---|---|
| committer | nanalelfe <nargiza.nosirova@mail.utoronto.ca> | 2016-07-27 00:03:35 +0000 |
| commit | 8beb37ed67b5f2fa0f9aa85499a8f11b39c9d067 (patch) | |
| tree | bd4b05a1e374b6cb10097bbcfbc12ef51c1cb85b /node_modules/express-minify/cache.js | |
| parent | 5e73fe37c32faf821d3d16f0251007e366cb090b (diff) | |
need pull
Diffstat (limited to 'node_modules/express-minify/cache.js')
| -rw-r--r-- | node_modules/express-minify/cache.js | 71 |
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; |
