Make static asset caching an option
This commit is contained in:
parent
1382ec47b2
commit
9ed330bdae
4 changed files with 12 additions and 7 deletions
|
@ -5,9 +5,10 @@ var winston = require('winston');
|
|||
|
||||
// For serving static assets
|
||||
|
||||
var StaticHandler = function(path) {
|
||||
var StaticHandler = function(path, cacheAssets) {
|
||||
this.basePath = path;
|
||||
this.defaultPath = '/index.html';
|
||||
this.cacheAssets = cacheAssets;
|
||||
// Grab the list of available files - and move into hash for quick lookup
|
||||
var available = fs.readdirSync(this.basePath);
|
||||
this.availablePaths = {};
|
||||
|
@ -36,9 +37,10 @@ StaticHandler.prototype.handle = function(incPath, response) {
|
|||
if (!this.availablePaths[incPath]) incPath = this.defaultPath;
|
||||
var filePath = this.basePath + (incPath == '/' ? this.defaultPath : incPath);
|
||||
// And then stream the file back - either from the cache or from source
|
||||
var cached = this.isCached(filePath);
|
||||
var cached = this.cacheAssets && this.isCached(filePath);
|
||||
var method = cached ? this.serveCached : this.retrieve;
|
||||
// Run!
|
||||
var _this = this;
|
||||
method(filePath, function(error, content) {
|
||||
// Get the content
|
||||
if (content) {
|
||||
|
@ -46,7 +48,7 @@ StaticHandler.prototype.handle = function(incPath, response) {
|
|||
response.writeHead(200, { 'content-type': contentType });
|
||||
response.end(content, 'utf-8');
|
||||
// Stick it in the cache if its not in there
|
||||
if (!cached) {
|
||||
if (!cached && _this.cacheAssets) {
|
||||
StaticHandler.cache[filePath] = content;
|
||||
}
|
||||
}
|
||||
|
@ -66,6 +68,7 @@ StaticHandler.prototype.handle = function(incPath, response) {
|
|||
// Retrieve from the file
|
||||
StaticHandler.prototype.retrieve = function(filePath, callback) {
|
||||
var _this = this;
|
||||
winston.verbose('loading static asset', { path: filePath });
|
||||
fs.readFile(filePath, function(error, content) {
|
||||
callback(error, content);
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue