cache static assets in memory

This commit is contained in:
John Crepezzi 2011-11-21 22:19:43 -05:00
parent e4da28de8a
commit 83cb68ada2
2 changed files with 26 additions and 2 deletions

View file

@ -16,6 +16,8 @@ var StaticHandler = function(path) {
}
};
StaticHandler.cache = {};
// Determine the content type for a given extension
StaticHandler.contentTypeFor = function(ext) {
if (ext == '.js') return 'text/javascript';
@ -34,6 +36,16 @@ 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
if (StaticHandler.cache[filePath]) {
this.serveCached(filePath, response);
}
else {
this.retrieve(filePath, response);
}
};
// Retrieve from the file
StaticHandler.prototype.retrieve = function(filePath, response) {
var _this = this;
fs.readFile(filePath, function(error, content) {
if (error) {
@ -45,8 +57,18 @@ StaticHandler.prototype.handle = function(incPath, response) {
var contentType = StaticHandler.contentTypeFor(path.extname(filePath));
response.writeHead(200, { 'content-type': contentType });
response.end(content, 'utf-8');
// Stick it in the cache
StaticHandler.cache[filePath] = content;
}
});
};
// Retrieve from memory cache
StaticHandler.prototype.serveCached = function(filePath, response) {
var contentType = StaticHandler.contentTypeFor(path.extname(filePath));
response.writeHead(200, { 'content-type': contentType });
response.end(StaticHandler.cache[filePath], 'utf-8');
};
module.exports = StaticHandler;