Node.js compression middleware.
$ npm install compressionvarcompression=require('compression')Returns the compression middleware using the given options.
app.use(compression({threshold: 512}))compression() accepts these properties in the options object. In addition to
those listed below, zlib options may be
passed in to the options object.
A function to decide if the response should be considered for compression.
This function is called as filter(req, res) and is expected to return
true to consider the response for compression, or false to not compress
the response.
The default filter function uses the compressible
module to determine if res.getHeader('Content-Type') is compressible.
The byte threshold for the response body size before compression is considered
for the response, defaults to 1kb. This is a number of bytes, any string
accepted by the bytes module, or false.
The default filter function. This is used to construct a custom filter
function that is an extension of the default function.
app.use(compression({filter: shouldCompress}))functionshouldCompress(req,res){if(req.headers['x-no-compression']){// don't compress responses with this request headerreturnfalse}// fallback to standard filter functionreturncompression.filter(req,res)}This module adds a res.flush() method to force the partially-compressed
response to be flushed to the client.
When using this module with express or connect, simply app.use the module as
high as you like. Requests that pass through the middleware will be compressed.
varcompression=require('compression')varexpress=require('express')varapp=express()// compress all requestsapp.use(compression())// add alll routesBecause 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.
varcompression=require('compression')varexpress=require('express')varapp=express()// compress responsesapp.use(compression())// server-sent event streamapp.get('/events',function(req,res){res.setHeader('Content-Type','text/event-stream')res.setHeader('Cache-Control','no-cache')// send a ping approx every 2 secondsvartimer=setInterval(function(){res.write('data: ping\n\n')// !!! this is the important partres.flush()},2000)res.on('close',function(){clearInterval(timer)})})