Categories
express gzip javascript middleware node.js

Merge, minify and serve JavaScript files with Express but the response is not gzipped

I’m using Express to build a web application. I want to merge, minify and serve .js files. I wrote a middleware, this is my code:

var fs = require('fs'),
path = require('path'),
uglify = require('uglify-js'),
cache="",
scriptsDir = path.join(__dirname, '../scripts'),
files = fs.readdirSync(scriptsDir);
// Sync read is not a problem since the following code is executed on startup
files.forEach(function(fname) {
if (/^.*\.js$/.test(fname)) {
cache += fs.readFileSync(path.join(scriptsDir, fname), 'utf8').toString();
}
});
cache = uglify.minify(cache, { fromString: true }).code;
module.exports = function(req, res, next) {
if (req.url === '/js/all.js')
res.end(cache);
else
next();
};

The middleware is used this way:

app.use(compress());
[...]
app.use(app.router);
app.use(jsMerger); // Here is my middleware
app.use(express.static(path.join(__dirname, '../public')));

The problem is the response is not gzipped. Also, there are “no headers” in the response (I mean, no cache headers, no etags; other resources served with the static middleware have those headers). This is the response:

X-Powered-By: Express
Transfer-Encoding: chunked
Date: Wed, 12 Mar 2014 14:04:19 GMT
Connection: keep-alive

Am I missing something? How to compress the response?