Skip to content

Instantly share code, notes, and snippets.

@erasmo-marin
Created April 3, 2017 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erasmo-marin/b8d019d9a143e2a59a4e2dc53c70bb97 to your computer and use it in GitHub Desktop.
Save erasmo-marin/b8d019d9a143e2a59a4e2dc53c70bb97 to your computer and use it in GitHub Desktop.
//this middleware serves all js files as gzip
app.use(function(req, res, next) {
var originalPath = req.path;
if(!originalPath.endsWith(".js")) {
next();
return;
}
try {
var stats = fs.statSync(path.join("public", `${req.path}.gz`));
res.append('Content-Encoding', 'gzip');
res.setHeader('Vary', 'Accept-Encoding');
res.setHeader('Cache-Control', 'public, max-age=512000');
req.url = `${req.url}.gz`;
var type = mime.lookup(path.join("public", originalPath));
if (typeof type != 'undefined') {
var charset = mime.charsets.lookup(type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
}
} catch(e) {
}
next();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment