You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

238 lines
7.6 KiB

3 months ago
  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. [![Test Coverage][coveralls-image]][coveralls-url]
  6. Node.js compression middleware.
  7. The following compression codings are supported:
  8. - deflate
  9. - gzip
  10. ## Install
  11. This is a [Node.js](https://nodejs.org/en/) module available through the
  12. [npm registry](https://www.npmjs.com/). Installation is done using the
  13. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  14. ```bash
  15. $ npm install compression
  16. ```
  17. ## API
  18. ```js
  19. var compression = require('compression')
  20. ```
  21. ### compression([options])
  22. Returns the compression middleware using the given `options`. The middleware
  23. will attempt to compress response bodies for all requests that traverse through
  24. the middleware, based on the given `options`.
  25. This middleware will never compress responses that include a `Cache-Control`
  26. header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4),
  27. as compressing will transform the body.
  28. #### Options
  29. `compression()` accepts these properties in the options object. In addition to
  30. those listed below, [zlib](http://nodejs.org/api/zlib.html) options may be
  31. passed in to the options object.
  32. ##### chunkSize
  33. The default value is `zlib.Z_DEFAULT_CHUNK`, or `16384`.
  34. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
  35. regarding the usage.
  36. ##### filter
  37. A function to decide if the response should be considered for compression.
  38. This function is called as `filter(req, res)` and is expected to return
  39. `true` to consider the response for compression, or `false` to not compress
  40. the response.
  41. The default filter function uses the [compressible](https://www.npmjs.com/package/compressible)
  42. module to determine if `res.getHeader('Content-Type')` is compressible.
  43. ##### level
  44. The level of zlib compression to apply to responses. A higher level will result
  45. in better compression, but will take longer to complete. A lower level will
  46. result in less compression, but will be much faster.
  47. This is an integer in the range of `0` (no compression) to `9` (maximum
  48. compression). The special value `-1` can be used to mean the "default
  49. compression level", which is a default compromise between speed and
  50. compression (currently equivalent to level 6).
  51. - `-1` Default compression level (also `zlib.Z_DEFAULT_COMPRESSION`).
  52. - `0` No compression (also `zlib.Z_NO_COMPRESSION`).
  53. - `1` Fastest compression (also `zlib.Z_BEST_SPEED`).
  54. - `2`
  55. - `3`
  56. - `4`
  57. - `5`
  58. - `6` (currently what `zlib.Z_DEFAULT_COMPRESSION` points to).
  59. - `7`
  60. - `8`
  61. - `9` Best compression (also `zlib.Z_BEST_COMPRESSION`).
  62. The default value is `zlib.Z_DEFAULT_COMPRESSION`, or `-1`.
  63. **Note** in the list above, `zlib` is from `zlib = require('zlib')`.
  64. ##### memLevel
  65. This specifies how much memory should be allocated for the internal compression
  66. state and is an integer in the range of `1` (minimum level) and `9` (maximum
  67. level).
  68. The default value is `zlib.Z_DEFAULT_MEMLEVEL`, or `8`.
  69. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
  70. regarding the usage.
  71. ##### strategy
  72. This is used to tune the compression algorithm. This value only affects the
  73. compression ratio, not the correctness of the compressed output, even if it
  74. is not set appropriately.
  75. - `zlib.Z_DEFAULT_STRATEGY` Use for normal data.
  76. - `zlib.Z_FILTERED` Use for data produced by a filter (or predictor).
  77. Filtered data consists mostly of small values with a somewhat random
  78. distribution. In this case, the compression algorithm is tuned to
  79. compress them better. The effect is to force more Huffman coding and less
  80. string matching; it is somewhat intermediate between `zlib.Z_DEFAULT_STRATEGY`
  81. and `zlib.Z_HUFFMAN_ONLY`.
  82. - `zlib.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing
  83. for a simpler decoder for special applications.
  84. - `zlib.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match).
  85. - `zlib.Z_RLE` Use to limit match distances to one (run-length encoding).
  86. This is designed to be almost as fast as `zlib.Z_HUFFMAN_ONLY`, but give
  87. better compression for PNG image data.
  88. **Note** in the list above, `zlib` is from `zlib = require('zlib')`.
  89. ##### threshold
  90. The byte threshold for the response body size before compression is considered
  91. for the response, defaults to `1kb`. This is a number of bytes or any string
  92. accepted by the [bytes](https://www.npmjs.com/package/bytes) module.
  93. **Note** this is only an advisory setting; if the response size cannot be determined
  94. at the time the response headers are written, then it is assumed the response is
  95. _over_ the threshold. To guarantee the response size can be determined, be sure
  96. set a `Content-Length` response header.
  97. ##### windowBits
  98. The default value is `zlib.Z_DEFAULT_WINDOWBITS`, or `15`.
  99. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
  100. regarding the usage.
  101. #### .filter
  102. The default `filter` function. This is used to construct a custom filter
  103. function that is an extension of the default function.
  104. ```js
  105. var compression = require('compression')
  106. var express = require('express')
  107. var app = express()
  108. app.use(compression({ filter: shouldCompress }))
  109. function shouldCompress (req, res) {
  110. if (req.headers['x-no-compression']) {
  111. // don't compress responses with this request header
  112. return false
  113. }
  114. // fallback to standard filter function
  115. return compression.filter(req, res)
  116. }
  117. ```
  118. ### res.flush
  119. This module adds a `res.flush()` method to force the partially-compressed
  120. response to be flushed to the client.
  121. ## Examples
  122. ### express/connect
  123. When using this module with express or connect, simply `app.use` the module as
  124. high as you like. Requests that pass through the middleware will be compressed.
  125. ```js
  126. var compression = require('compression')
  127. var express = require('express')
  128. var app = express()
  129. // compress all responses
  130. app.use(compression())
  131. // add all routes
  132. ```
  133. ### Server-Sent Events
  134. Because of the nature of compression this module does not work out of the box
  135. with server-sent events. To compress content, a window of the output needs to
  136. be buffered up in order to get good compression. Typically when using server-sent
  137. events, there are certain block of data that need to reach the client.
  138. You can achieve this by calling `res.flush()` when you need the data written to
  139. actually make it to the client.
  140. ```js
  141. var compression = require('compression')
  142. var express = require('express')
  143. var app = express()
  144. // compress responses
  145. app.use(compression())
  146. // server-sent event stream
  147. app.get('/events', function (req, res) {
  148. res.setHeader('Content-Type', 'text/event-stream')
  149. res.setHeader('Cache-Control', 'no-cache')
  150. // send a ping approx every 2 seconds
  151. var timer = setInterval(function () {
  152. res.write('data: ping\n\n')
  153. // !!! this is the important part
  154. res.flush()
  155. }, 2000)
  156. res.on('close', function () {
  157. clearInterval(timer)
  158. })
  159. })
  160. ```
  161. ## License
  162. [MIT](LICENSE)
  163. [npm-image]: https://img.shields.io/npm/v/compression.svg
  164. [npm-url]: https://npmjs.org/package/compression
  165. [coveralls-image]: https://img.shields.io/coveralls/expressjs/compression/master.svg
  166. [coveralls-url]: https://coveralls.io/r/expressjs/compression?branch=master
  167. [downloads-image]: https://img.shields.io/npm/dm/compression.svg
  168. [downloads-url]: https://npmjs.org/package/compression
  169. [github-actions-ci-image]: https://badgen.net/github/checks/expressjs/compression/master?label=ci
  170. [github-actions-ci-url]: https://github.com/expressjs/compression/actions?query=workflow%3Aci