Skip to content

Instantly share code, notes, and snippets.

@jankuca
Created November 12, 2011 16:40
Show Gist options
  • Save jankuca/1360787 to your computer and use it in GitHub Desktop.
Save jankuca/1360787 to your computer and use it in GitHub Desktop.
gzip for native node.js http.Server
var http = require('http');
var gzip = require('http-gzip');
var server = http.createServer(function (req, res) {
gzip(req, res);
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('I am gonna be gzip encoded, dude!');
res.end();
});
server.listen(80);
/**
* gzip
* a simple layer for the native node.js http.Server
* @author Jan Kuča <[email protected]>, http://jankuca.com
*/
var spawn = require('child_process').spawn;
/**
* @param {http.ServerRequest} req
* @param {http.ServerResponse} res
* @return {boolean} Whether gzip encoding takes place
*/
function gzip(req, res) {
// check if the client accepts gzip
var header = req.headers['accept-encoding'];
var accepts = Boolean(header && /gzip/i.test(header));
if (!accepts) return false;
// store native methods
var writeHead = res.writeHead;
var write = res.write;
var end = res.end;
var gzip = spawn('gzip');
gzip.stdout.on('data', function (chunk) {
try {
write.call(res, chunk);
} catch (err) {
}
});
gzip.on('exit', function () {
end.call(res);
});
// duck punch gzip piping
res.writeHead = function (status, headers) {
headers = headers || {};
if (Array.isArray(headers)) {
headers.push([ 'content-encoding', 'gzip' ]);
} else {
headers['content-encoding'] = 'gzip';
}
writeHead.call(res, status, headers);
};
res.write = function (chunk) {
gzip.stdin.write(chunk);
};
res.end = function () {
gzip.stdin.end();
};
return true;
};
module.exports = gzip;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment