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.

240 lines
7.5 KiB

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