Commit 83cb68ad authored by John Crepezzi's avatar John Crepezzi
Browse files

cache static assets in memory

parent e4da28de
Loading
Loading
Loading
Loading
+4 −2
Original line number Diff line number Diff line
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
+22 −0
Original line number Diff line number Diff line
@@ -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;