Skip to content

Commit

Permalink
Trying to get streaming gzip to work
Browse files Browse the repository at this point in the history
  • Loading branch information
tomgco committed May 24, 2011
1 parent 0074709 commit 78867da
Showing 1 changed file with 34 additions and 12 deletions.
46 changes: 34 additions & 12 deletions lib/gzip.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,7 @@
/**
* Module dependencies.
*/

var fs = require('fs'),
parse = require('url').parse,
path = require('path'),
mime = require('mime'),
compress = require('compress'),
staticSend = require('connect').static.send;
var compress = require('compress');

/**
* gzipped cache.
Expand All @@ -25,7 +19,7 @@ var gzippoCache = {};
* gzip file.
*/

var gzippo = function(data) {
var gzippo = function(data, url) {
var gzip = new compress.Gzip();
gzip.init();
var gzippedData = gzip.deflate(data, 'binary') + gzip.end();
Expand Down Expand Up @@ -61,36 +55,64 @@ var gzippo = function(data) {
exports = module.exports = function gzip(options){
options = options || {};
var maxAge = options.maxAge || 86400000,
contentTypeMatch = options.contentTypeMatch || /text/;
contentTypeMatch = options.contentTypeMatch || /text|javascript|json/;

if (!contentTypeMatch.test) throw new Error('contentTypeMatch: must be a regular expression.');

return function gzip(req, res, next){
var end = res.end,
writeHead = res.writeHead,
setHeader = res.setHeader,
url = req.originalUrl,
defaults = {};
write = res.write,
send = res.send,
defaults = {},
chunky = '';

// mount safety
if (req._gzipping) return next();

res.setHeader = function(key, value){
res.setHeader = setHeader;
if (key == "Content-Type" && contentTypeMatch.test(value)) {
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Vary', 'Accept-Encoding');
}
res.setHeader(key, value);
};

res.writeHead = function(code, headers){
res.writeHead = writeHead;
contentType = res._headers['content-type'] || '';
if (contentTypeMatch.test(contentType)) {
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Vary', 'Accept-Encoding');
res.removeHeader('Content-Length');
}
res.writeHead(code, headers);
};

res.write = function(chunk, encoding) {
res.write = write;
contentType = res._headers['content-type'] || '';
if (contentTypeMatch.test(contentType)) {
chunky += chunk;
} else {
res.write(chunk, encoding);
}
};

res.end = function(chunk, encoding) {
res.end = end;
contentType = res._headers['content-type'] || '';
if (contentTypeMatch.test(contentType) && !req._gzipping) {
chunk = gzippo(chunk);
req._gzipping = true;
res.setHeader('Content-Length', chunk.length);
if (chunk !== undefined) {
chunky += chunk;
}
console.log(chunky);
chunk = gzippo(chunky);
chunky = '';
res.end(chunk, 'binary');
} else {
res.end(chunk, encoding);
Expand Down

0 comments on commit 78867da

Please sign in to comment.