Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lyhcode
Created April 2, 2012 10:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lyhcode/2282472 to your computer and use it in GitHub Desktop.
Save lyhcode/2282472 to your computer and use it in GitHub Desktop.
Node.js + Gzip/Deflate Compression
var zlib = require('zlib');
var compress = function(req, res, result) {
var acceptEncoding = req.headers['accept-encoding'];
if (!acceptEncoding) { acceptEncoding = ''; }
if (acceptEncoding.match(/\bdeflate\b/)) {
zlib.deflate(result, function(err, result) {
if (!err) {
res.writeHead(200, { 'content-encoding': 'deflate' });
res.send(result);
}
});
} else if (acceptEncoding.match(/\bgzip\b/)) {
zlib.gzip(result, function(err, result){
if (!err) {
res.writeHead(200, { 'content-encoding': 'gzip' });
res.send(result);
}
});
} else {
res.writeHead(200, {});
res.send(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment