Skip to content

Commit

Permalink
Added override for writeHead to remove any 'content-length' garbage
Browse files Browse the repository at this point in the history
  • Loading branch information
beatgammit committed Jul 16, 2011
1 parent c3a0713 commit 0b9b8cc
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions lib/squish.js
Expand Up @@ -48,14 +48,28 @@
var outStream,
twrite,
tend,
twriteHead,
first = true;

outStream = construct(compressor.constructor, compressor.args);
twrite = res.write;
twriteHead = res.writeHead;
tend = res.end;

// set the headers and override response write functions
res.setHeader('Content-Encoding', compressor.type);
try {
// set the headers and override response write functions
res.setHeader('Content-Encoding', compressor.type);

// compressing changes the length, so we need ta make sure
// that Content-Length isn't set or the request won't end
res.removeHeader('content-cength');
} catch (e) {
console.error('Squish could not manipulate headers.');
console.error('A response has probably been started but not ended.');
console.error('Abandoning ship (you should probably fix this).');

throw e;
}

outStream.on('data', function (data) {
twrite.call(res, data, 'binary');
Expand All @@ -66,19 +80,32 @@
tend.call(res);
});

res.writeHead = function (statusCode, reasonPhrase, headers) {
if (typeof reasonPhrase !== 'string') {
headers = reasonPhrase;
}

if (headers) {
if (headers['content-length']) {
delete headers['content-length'];
}
}
if (this._headers) {
if (this._headers['content-length']) {
delete this._headers['content-length'];
}
}

twriteHead.apply(this, arguments);
};

res.write = function (chunk, encoding) {
var buffer;

if (chunk) {
buffer = createBuffer(chunk, encoding);

// compressing changes the length, so we need ta make sure
// that Content-Length isn't set or the request won't end
if (first) {
res.removeHeader('Content-Length');

first = false;
}
first = false;

outStream.write(buffer);
}
Expand Down

0 comments on commit 0b9b8cc

Please sign in to comment.