Created
November 12, 2011 16:40
-
-
Save jankuca/1360787 to your computer and use it in GitHub Desktop.
gzip for native node.js http.Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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