Permalink
Browse files

Added zlib/gzip support

  • Loading branch information...
1 parent 37a9946 commit f90be3e426fc6b564734a403d3be90e54261afb3 @ryanrolds ryanrolds committed Jan 24, 2012
Showing with 42 additions and 5 deletions.
  1. +42 −5 lib/assetmanager.js
View
@@ -7,6 +7,12 @@ var fs = require('fs')
, cssmin = require('./../deps/cssmin').minify
, crypto = require('crypto');
+// this is lame, I know. Will fix later
+var zlib;
+try {
+ zlib = require('zlib');
+} catch(e) {}
+
var cache = {}
, settings = {}
, cacheHashes = {}
@@ -237,8 +243,25 @@ module.exports = function assetManager (assets) {
cacheHashes[groupName] = crypto.createHash('md5').update(content).digest('hex');
- cache[groupName][match].contentBuffer = new Buffer(content, 'utf8');
- cache[groupName][match].contentLength = cache[groupName][match].contentBuffer.length;
+ cache[groupName][match].encodings = {};
+ var encodings = cache[groupName][match].encodings;
+
+ var utf8Buffer = new Buffer(content, 'utf8');
+ encodings.utf8 = {
+ 'buffer': utf8Buffer,
+ 'length': utf8Buffer.length,
+ 'encoding': 'utf8'
+ };
+
+ if(zlib) {
+ var gzipBuffer = zlib.gzip(utf8Buffer, function(error, result) {
+ encodings.gzip = {
+ 'buffer': result,
+ 'length': result.length,
+ 'encoding': 'gzip'
+ };
+ });
+ }
});
});
});
@@ -302,6 +325,11 @@ module.exports = function assetManager (assets) {
}
};
+ this.acceptsGzip = function(req) {
+ var accept = req.headers["accept-encoding"];
+ return accept && accept.toLowerCase().indexOf('gzip') !== -1;
+ }
+
function assetManager (req, res, next) {
var self = this;
var found = false;
@@ -325,10 +353,18 @@ module.exports = function assetManager (assets) {
Object.keys(cache[groupName]).forEach(function(match) {
if (!found && userAgent.match(new RegExp(match, 'i'))) {
found = true;
+ var item = cache[groupName][match];
+
+ var content = item.encodings.utf8;
+ if(zlib && item.encodings.gzip && this.acceptsGzip(req)) {
+ content = item.encodings.gzip;
+ }
+
response = {
- contentLength: cache[groupName][match].contentLength
- , modified: cache[groupName][match].modified
- , contentBuffer: cache[groupName][match].contentBuffer
+ contentLength: content.length
+ , modified: item.modified
+ , contentBuffer: content.buffer
+ , encoding: content.encoding
};
}
});
@@ -353,6 +389,7 @@ module.exports = function assetManager (assets) {
'Last-Modified': response.modified,
'Date': (new Date).toUTCString(),
'Cache-Control': 'public max-age=' + 31536000,
+ 'Content-Encoding': response.encoding,
'Expires': response.expires || (new Date(new Date().getTime()+63113852000)).toUTCString()
});
res.end(response.contentBuffer);

0 comments on commit f90be3e

Please sign in to comment.