Skip to content

Commit 715e4f5

Browse files
committed
refactored compress()
1 parent 13a9ff8 commit 715e4f5

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

lib/middleware/compress.js

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,30 @@ module.exports = function compress(options) {
7272
, stream
7373
, method;
7474

75+
// proxy
76+
77+
res.write = function(chunk){
78+
if (!res.headerSent) this._implicitHeader();
79+
return stream.write(chunk);
80+
};
81+
82+
res.end = function(chunk){
83+
if (chunk) stream.write(chunk);
84+
return stream.end();
85+
};
86+
87+
function revert() {
88+
stream = res;
89+
res.write = write;
90+
res.end = end;
91+
}
92+
7593
res.on('header', function(){
7694
// default request filter
77-
if (!filter(req, res)) return;
95+
if (!filter(req, res)) return revert();
7896

7997
// SHOULD use identity
80-
if (!accept) return;
98+
if (!accept) return revert();
8199

82100
// default to gzip
83101
if ('*' == accept.trim()) method = 'gzip';
@@ -93,7 +111,7 @@ module.exports = function compress(options) {
93111
}
94112

95113
// compression method
96-
if (!method) return;
114+
if (!method) return revert();
97115

98116
// compression stream
99117
stream = exports.methods[method](options);
@@ -102,17 +120,6 @@ module.exports = function compress(options) {
102120
res.setHeader('Content-Encoding', method);
103121
res.setHeader('Vary', 'Accept-Encoding');
104122

105-
// proxy
106-
107-
res.write = function(chunk){
108-
return stream.write(chunk);
109-
};
110-
111-
res.end = function(chunk){
112-
if (chunk) stream.write(chunk);
113-
return stream.end();
114-
};
115-
116123
// compression
117124

118125
stream.on('data', function(chunk){

0 commit comments

Comments
 (0)