Permalink
Browse files

Initial implementation of gzip-static middleware

We check if compressed version of the file is available. If it is we
stream it, if not we let static middleware handle everything else.
  • Loading branch information...
pirxpilot committed Sep 17, 2013
1 parent 0ef6740 commit 7ef679d42676152b6d0327168bdcf572045daa4a
Showing with 78 additions and 0 deletions.
  1. +15 −0 Readme.md
  2. +1 −0 index.js
  3. +57 −0 lib/gzip-static.js
  4. +5 −0 package.json
@@ -13,11 +13,26 @@ connect-static if they don't
## Options
gzip-static is meant to be a drop in replacement for [connect static][] middleware. Use the same
options as you would with [connect static][].
## Usage
```javascript
var gzipStatic = require('connect-gzip-static');
var oneDay = 86400000;
connect()
.use(gzipStaticconnect.static(__dirname + '/public'))
connect()
.use(gzipStatic(__dirname + '/public', { maxAge: oneDay }))
```
# License
MIT
[connect]: http://www.senchalabs.org/connect
[connect static]: http://www.senchalabs.org/connect/static.html
@@ -0,0 +1 @@
module.exports = require('./lib/gzip-static');
@@ -0,0 +1,57 @@
var send = require('send');
var connect = require('connect');
var debug = require('debug')('connect:gzip-static');
var utils = connect.utils;
var fs = require('fs');
var path = require('path');
var mime = send.mime;
function setHeader(res, path) {
var type = mime.lookup(path);
var charset = mime.charsets.lookup(type);
debug('content-type %s', type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Vary', 'Accept-Encoding');
}
module.exports = function(root, options) {
var static;
options = options || {};
static = connect.static(root, options);
return function gzipStatic(req, res, next) {
var acceptEncoding, passToStatic, name = {};
passToStatic = static.bind(this, req, res, next);
acceptEncoding = req.headers['accept-encoding'] || '';
if (!~acceptEncoding.indexOf('gzip')) {
debug('Passing %s', req.url);
return passToStatic();
}
name.orig = utils.parseUrl(req).pathname;
name.gz = name.orig + '.gz';
name.full = path.join(root, name.gz);
fs.stat(name.full, function(err, stat) {
var exists = !err && stat.isFile();
if (!exists) {
debug('Passing %s', req.url);
return passToStatic();
}
debug('Sending %s', name.full);
setHeader(res, name.orig);
send(req, name.gz)
.maxage(options.maxAge || 0)
.root(root)
.hidden(options.hidden)
.on('error', next)
.pipe(res);
});
};
};
@@ -21,6 +21,11 @@
"bugs": {
"url": "https://github.com/code42day/connect-gzip-static/issues"
},
"dependencies": {
"debug": "~0",
"send": "~0",
"connect": ">=2"
},
"devDependencies": {
"jshint": "~2.1.10",
"mocha": "~1.13.0"

0 comments on commit 7ef679d

Please sign in to comment.