cc8457aec768199b36a1de2080e61731dd386f6e557c64bfb4a3a86ad7a62543d7d9530a44b219deb2b9b200e2e038865afd89e72cc03d6634a27638bf5371 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. # compression
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Build Status][github-actions-ci-image]][github-actions-ci-url]
  5. [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
  6. [![Funding][funding-image]][funding-url]
  7. Node.js compression middleware.
  8. The following compression codings are supported:
  9. - deflate
  10. - gzip
  11. - br (brotli)
  12. **Note** Brotli is supported only since Node.js versions v11.7.0 and v10.16.0.
  13. ## Install
  14. This is a [Node.js](https://nodejs.org/en/) module available through the
  15. [npm registry](https://www.npmjs.com/). Installation is done using the
  16. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  17. ```bash
  18. $ npm install compression
  19. ```
  20. ## API
  21. ```js
  22. var compression = require('compression')
  23. ```
  24. ### compression([options])
  25. Returns the compression middleware using the given `options`. The middleware
  26. will attempt to compress response bodies for all requests that traverse through
  27. the middleware, based on the given `options`.
  28. This middleware will never compress responses that include a `Cache-Control`
  29. header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4),
  30. as compressing will transform the body.
  31. #### Options
  32. `compression()` accepts these properties in the options object. In addition to
  33. those listed below, [zlib](http://nodejs.org/api/zlib.html) options may be
  34. passed in to the options object or
  35. [brotli](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) options.
  36. ##### chunkSize
  37. Type: `Number`<br>
  38. Default: `zlib.constants.Z_DEFAULT_CHUNK`, or `16384`.
  39. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
  40. regarding the usage.
  41. ##### filter
  42. Type: `Function`
  43. A function to decide if the response should be considered for compression.
  44. This function is called as `filter(req, res)` and is expected to return
  45. `true` to consider the response for compression, or `false` to not compress
  46. the response.
  47. The default filter function uses the [compressible](https://www.npmjs.com/package/compressible)
  48. module to determine if `res.getHeader('Content-Type')` is compressible.
  49. ##### level
  50. Type: `Number`<br>
  51. Default: `zlib.constants.Z_DEFAULT_COMPRESSION`, or `-1`
  52. The level of zlib compression to apply to responses. A higher level will result
  53. in better compression, but will take longer to complete. A lower level will
  54. result in less compression, but will be much faster.
  55. This is an integer in the range of `0` (no compression) to `9` (maximum
  56. compression). The special value `-1` can be used to mean the "default
  57. compression level", which is a default compromise between speed and
  58. compression (currently equivalent to level 6).
  59. - `-1` Default compression level (also `zlib.constants.Z_DEFAULT_COMPRESSION`).
  60. - `0` No compression (also `zlib.constants.Z_NO_COMPRESSION`).
  61. - `1` Fastest compression (also `zlib.constants.Z_BEST_SPEED`).
  62. - `2`
  63. - `3`
  64. - `4`
  65. - `5`
  66. - `6` (currently what `zlib.constants.Z_DEFAULT_COMPRESSION` points to).
  67. - `7`
  68. - `8`
  69. - `9` Best compression (also `zlib.constants.Z_BEST_COMPRESSION`).
  70. **Note** in the list above, `zlib` is from `zlib = require('zlib')`.
  71. ##### memLevel
  72. Type: `Number`<br>
  73. Default: `zlib.constants.Z_DEFAULT_MEMLEVEL`, or `8`
  74. This specifies how much memory should be allocated for the internal compression
  75. state and is an integer in the range of `1` (minimum level) and `9` (maximum
  76. level).
  77. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
  78. regarding the usage.
  79. ##### brotli
  80. Type: `Object`
  81. This specifies the options for configuring Brotli. See [Node.js documentation](https://nodejs.org/api/zlib.html#class-brotlioptions) for a complete list of available options.
  82. ##### strategy
  83. Type: `Number`<br>
  84. Default: `zlib.constants.Z_DEFAULT_STRATEGY`
  85. This is used to tune the compression algorithm. This value only affects the
  86. compression ratio, not the correctness of the compressed output, even if it
  87. is not set appropriately.
  88. - `zlib.constants.Z_DEFAULT_STRATEGY` Use for normal data.
  89. - `zlib.constants.Z_FILTERED` Use for data produced by a filter (or predictor).
  90. Filtered data consists mostly of small values with a somewhat random
  91. distribution. In this case, the compression algorithm is tuned to
  92. compress them better. The effect is to force more Huffman coding and less
  93. string matching; it is somewhat intermediate between `zlib.constants.Z_DEFAULT_STRATEGY`
  94. and `zlib.constants.Z_HUFFMAN_ONLY`.
  95. - `zlib.constants.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing
  96. for a simpler decoder for special applications.
  97. - `zlib.constants.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match).
  98. - `zlib.constants.Z_RLE` Use to limit match distances to one (run-length encoding).
  99. This is designed to be almost as fast as `zlib.constants.Z_HUFFMAN_ONLY`, but give
  100. better compression for PNG image data.
  101. **Note** in the list above, `zlib` is from `zlib = require('zlib')`.
  102. ##### threshold
  103. Type: `Number` or `String`<br>
  104. Default: `1kb`
  105. The byte threshold for the response body size before compression is considered
  106. for the response. This is a number of bytes or any string
  107. accepted by the [bytes](https://www.npmjs.com/package/bytes) module.
  108. **Note** this is only an advisory setting; if the response size cannot be determined
  109. at the time the response headers are written, then it is assumed the response is
  110. _over_ the threshold. To guarantee the response size can be determined, be sure
  111. set a `Content-Length` response header.
  112. ##### windowBits
  113. Type: `Number`<br>
  114. Default: `zlib.constants.Z_DEFAULT_WINDOWBITS`, or `15`
  115. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
  116. regarding the usage.
  117. ##### enforceEncoding
  118. Type: `String`<br>
  119. Default: `identity`
  120. This is the default encoding to use when the client does not specify an encoding in the request's [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header.
  121. #### .filter
  122. The default `filter` function. This is used to construct a custom filter
  123. function that is an extension of the default function.
  124. ```js
  125. var compression = require('compression')
  126. var express = require('express')
  127. var app = express()
  128. app.use(compression({ filter: shouldCompress }))
  129. function shouldCompress (req, res) {
  130. if (req.headers['x-no-compression']) {
  131. // don't compress responses with this request header
  132. return false
  133. }
  134. // fallback to standard filter function
  135. return compression.filter(req, res)
  136. }
  137. ```
  138. ### res.flush
  139. This module adds a `res.flush()` method to force the partially-compressed
  140. response to be flushed to the client.
  141. ## Examples
  142. ### express
  143. When using this module with express, simply `app.use` the module as
  144. high as you like. Requests that pass through the middleware will be compressed.
  145. ```js
  146. var compression = require('compression')
  147. var express = require('express')
  148. var app = express()
  149. // compress all responses
  150. app.use(compression())
  151. // add all routes
  152. ```
  153. ### Node.js HTTP server
  154. ```js
  155. var compression = require('compression')({ threshold: 0 })
  156. var http = require('http')
  157. function createServer (fn) {
  158. return http.createServer(function (req, res) {
  159. compression(req, res, function (err) {
  160. if (err) {
  161. res.statusCode = err.status || 500
  162. res.end(err.message)
  163. return
  164. }
  165. fn(req, res)
  166. })
  167. })
  168. }
  169. var server = createServer(function (req, res) {
  170. res.setHeader('Content-Type', 'text/plain')
  171. res.end('hello world!')
  172. })
  173. server.listen(3000, () => {
  174. console.log('> Listening at http://localhost:3000')
  175. })
  176. ```
  177. ### Server-Sent Events
  178. Because of the nature of compression this module does not work out of the box
  179. with server-sent events. To compress content, a window of the output needs to
  180. be buffered up in order to get good compression. Typically when using server-sent
  181. events, there are certain block of data that need to reach the client.
  182. You can achieve this by calling `res.flush()` when you need the data written to
  183. actually make it to the client.
  184. ```js
  185. var compression = require('compression')
  186. var express = require('express')
  187. var app = express()
  188. // compress responses
  189. app.use(compression())
  190. // server-sent event stream
  191. app.get('/events', function (req, res) {
  192. res.setHeader('Content-Type', 'text/event-stream')
  193. res.setHeader('Cache-Control', 'no-cache')
  194. // send a ping approx every 2 seconds
  195. var timer = setInterval(function () {
  196. res.write('data: ping\n\n')
  197. // !!! this is the important part
  198. res.flush()
  199. }, 2000)
  200. res.on('close', function () {
  201. clearInterval(timer)
  202. })
  203. })
  204. ```
  205. ## Contributing
  206. The Express.js project welcomes all constructive contributions. Contributions take many forms,
  207. from code for bug fixes and enhancements, to additions and fixes to documentation, additional
  208. tests, triaging incoming pull requests and issues, and more!
  209. See the [Contributing Guide](https://github.com/expressjs/express/blob/master/Contributing.md) for more technical details on contributing.
  210. ## License
  211. [MIT](LICENSE)
  212. [npm-image]: https://badgen.net/npm/v/compression
  213. [npm-url]: https://npmjs.org/package/compression
  214. [downloads-image]: https://badgen.net/npm/dm/compression
  215. [downloads-url]: https://npmcharts.com/compare/compression?minimal=true
  216. [github-actions-ci-image]: https://badgen.net/github/checks/expressjs/compression/master?label=CI
  217. [github-actions-ci-url]: https://github.com/expressjs/compression/actions?query=workflow%3Aci
  218. [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/compression/badge
  219. [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/compression
  220. [funding-url]: https://opencollective.com/express
  221. [funding-image]: https://badgen.net/badge/icon/sponsor/pink?icon=github&label=Open%20Collective