compression
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
accepts | 1.2.13 | 4.7 kB | MIT | prod | 1 |
bytes | 2.1.0 | 2.31 kB | MIT | prod | |
compressible | 2.0.18 | 3 kB | MIT | prod | |
debug | 2.2.0 | 10.05 kB | MIT | prod | 1 1 2 |
on-headers | 1.0.2 | 3.15 kB | MIT | prod | |
vary | 1.0.1 | 3 kB | MIT | prod |
The "compression" is a Node.js middleware that aims to compress response bodies for all requests that go through the middleware. It supports two compression codings: "deflate" and "gzip". This is handy for efficient data handling in your Node.js web application, resulting in decreased load times and improved performance due to less data being transferred over the network.
To install the "compression" middleware, simply use the npm install command in your terminal like so:
$ npm install compression
Then, you require the compression middleware and use it in your application as illustrated in the following example:
var compression = require('compression')
var express = require('express')
var app = express()
// compress all responses
app.use(compression())
// add all routes
This example demonstrates compression being used with the Express.js library. By using the middleware via the app.use(compression())
call, all responses of your Express.js application will be compressed.
For more advanced usage, you can customise the behaviour by passing an options object to the compression function as demonstrated:
var compression = require('compression')
var express = require('express')
var app = express()
app.use(compression({ filter: shouldCompress }))
function shouldCompress (req, res) {
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false
}
// fallback to standard filter function
return compression.filter(req, res)
}
In this example, the filter
option is used to determine whether the response should be compressed or not.
For comprehensive information about the compression middleware, the API, and various usage scenarios, it is best to refer to the official GitHub repository at git+https://github.com/expressjs/compression.git. There is no separate documentation site, but the readme file in the GitHub repo provides extensive information, including more detailed code examples and a full rundown of all the possible configuration options and their usage. The module can also be found on npm at https://npmjs.org/package/compression.