From 83cb68ada26d05ef174a1149cfe5bf3ea5e6565d Mon Sep 17 00:00:00 2001 From: John Crepezzi Date: Mon, 21 Nov 2011 22:19:43 -0500 Subject: [PATCH] cache static assets in memory --- TODO | 6 ++++-- lib/static_handler.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/TODO b/TODO index 2b52991..41ff748 100644 --- a/TODO +++ b/TODO @@ -1,10 +1,12 @@ cache headers for static assets (and on document GET) tests add FAVICON (or force 404) -cache static in memory add feedback for errors to UI - esp. too long -copy URL to clipboard button add about page +make asset caching optional +todo store buffer instead of string while grabbing contents (if possible) +write cache to use callback instead of using non-DRY code # shared version only some way to do announcements easily (and use for ads) +copy URL to clipboard button diff --git a/lib/static_handler.js b/lib/static_handler.js index 89b93c0..07e2f47 100644 --- a/lib/static_handler.js +++ b/lib/static_handler.js @@ -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;