@@ -49,7 +49,7 @@ function compression(options) {
4949 }
5050
5151 return function compression ( req , res , next ) {
52- var compress = true
52+ var length
5353 var listeners = [ ]
5454 var write = res . write
5555 var on = res . on
@@ -68,34 +68,26 @@ function compression(options) {
6868
6969 res . write = function ( chunk , encoding ) {
7070 if ( ! this . _header ) {
71- // if content-length is set and is lower
72- // than the threshold, don't compress
73- var len = Number ( res . getHeader ( 'Content-Length' ) )
74- checkthreshold ( len )
75- this . _implicitHeader ( ) ;
71+ this . _implicitHeader ( )
7672 }
73+
7774 return stream
7875 ? stream . write ( new Buffer ( chunk , encoding ) )
79- : write . call ( res , chunk , encoding ) ;
76+ : write . call ( this , chunk , encoding )
8077 } ;
8178
8279 res . end = function ( chunk , encoding ) {
83- var len
84-
85- if ( chunk ) {
86- len = Buffer . isBuffer ( chunk )
87- ? chunk . length
88- : Buffer . byteLength ( chunk , encoding )
89- }
90-
9180 if ( ! this . _header ) {
92- len = Number ( this . getHeader ( 'Content-Length' ) ) || len
93- checkthreshold ( len )
81+ // estimate the length
82+ if ( ! this . getHeader ( 'Content-Length' ) ) {
83+ length = chunkLength ( chunk , encoding )
84+ }
85+
9486 this . _implicitHeader ( )
9587 }
9688
9789 if ( ! stream ) {
98- return end . call ( res , chunk , encoding )
90+ return end . call ( this , chunk , encoding )
9991 }
10092
10193 // write Buffer for Node.js 0.8
@@ -119,15 +111,8 @@ function compression(options) {
119111 return this
120112 }
121113
122- function checkthreshold ( len ) {
123- if ( compress && len < threshold ) {
124- debug ( 'size below threshold' )
125- compress = false
126- }
127- }
128-
129114 function nocompress ( msg ) {
130- debug ( 'no compression' + ( msg ? ': ' + msg : '' ) )
115+ debug ( 'no compression: %s' , msg )
131116 addListeners ( res , on , listeners )
132117 listeners = null
133118 }
@@ -142,8 +127,9 @@ function compression(options) {
142127 // vary
143128 vary ( res , 'Accept-Encoding' )
144129
145- if ( ! compress ) {
146- nocompress ( )
130+ // content-length below threshold
131+ if ( Number ( res . getHeader ( 'Content-Length' ) ) < threshold || length < threshold ) {
132+ nocompress ( 'size below threshold' )
147133 return
148134 }
149135
@@ -225,6 +211,20 @@ function addListeners(stream, on, listeners) {
225211 }
226212}
227213
214+ /**
215+ * Get the length of a given chunk
216+ */
217+
218+ function chunkLength ( chunk , encoding ) {
219+ if ( ! chunk ) {
220+ return
221+ }
222+
223+ return ! Buffer . isBuffer ( chunk )
224+ ? Buffer . byteLength ( chunk , encoding )
225+ : chunk . length
226+ }
227+
228228/**
229229 * No-operation function
230230 * @private
0 commit comments