What is compression?
The compression npm package is a middleware for Node.js that enables response compression, typically used with Express.js. It can compress response bodies for requests that traverse through the middleware, thus reducing the size of the response sent to clients and improving web application performance.
What are compression's main functionalities?
Compress response bodies
This code demonstrates how to use the compression middleware in an Express.js application to compress response bodies for all routes.
const express = require('express');
const compression = require('compression');
const app = express();
// Use compression middleware
app.use(compression());
// Example route
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
Filter requests to compress
This code shows how to use a custom filter function to decide whether to compress responses based on the request headers.
const express = require('express');
const compression = require('compression');
const app = express();
// Compression options with filter
const shouldCompress = (req, res) => {
if (req.headers['x-no-compression']) {
// Don't compress responses if this request header is present
return false;
}
// Fallback to the standard compression filter function
return compression.filter(req, res);
};
app.use(compression({ filter: shouldCompress }));
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
Other packages similar to compression
shrink-ray-current
shrink-ray-current is an npm package that offers response compression using Brotli and Zopfli, which can provide better compression ratios than the default zlib library used by compression. It is a modern alternative to compression with additional features like cache-friendly ETag support and streaming compression.
koa-compress
koa-compress is a compression middleware for Koa, another popular Node.js web framework. It provides similar functionality to compression but is designed specifically for the Koa ecosystem. It supports various compression algorithms like gzip, deflate, and brotli.
fastify-compress
fastify-compress is a plugin for the Fastify web framework that provides response compression capabilities. It supports 'gzip', 'deflate', and 'brotli' encoding methods and allows for custom compression options. It is similar to compression but tailored for use with Fastify.
compression
![Coverage Status](https://img.shields.io/coveralls/expressjs/compression.svg?branch=master)
Node.js compression middleware.
Install
$ npm install compression
API
var express = require('express')
var compression = require('compression')
var app = express()
app.use(compression())
compression(options)
Returns the compression middleware using the given options
.
app.use(compression({
threshold: 512
}))
Options
threshold
<1kb>
- response is only compressed if the byte size is at or above this threshold.filter
- a filtering callback function. Uses Compressible by default.
In addition to these, zlib options may be passed in to the options object.
res.flush
This module adds a res.flush()
method to force the partially-compressed
response to be flushed to the client.
Examples
Server-Sent Events
Because of the nature of compression this module does not work out of the box
with server-sent events. To compress content, a window of the output needs to
be buffered up in order to get good compression. Typically when using server-sent
events, there are certain block of data that need to reach the client.
You can achieve this by calling res.flush()
when you need the data written to
actually make it to the client.
var compression = require('compression')
var express = require('express')
var app = express()
app.use(compression())
app.get('/events', function (req, res) {
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
var timer = setInterval(function () {
res.write('data: ping\n\n')
res.flush()
}, 2000)
res.on('close', function () {
clearInterval(timer)
})
})
License
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.