Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork242
Node.js compression middleware
License
expressjs/compression
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Node.js compression middleware.
The following compression codings are supported:
- deflate
- gzip
- br (brotli)
Note Brotli is supported only since Node.js versions v11.7.0 and v10.16.0.
This is aNode.js module available through thenpm registry. Installation is done using thenpm install command:
$ npm install compression
varcompression=require('compression')
Returns the compression middleware using the givenoptions. The middlewarewill attempt to compress response bodies for all requests that traverse throughthe middleware, based on the givenoptions.
This middleware will never compress responses that include aCache-Controlheader with theno-transform directive,as compressing will transform the body.
compression() accepts these properties in the options object. In addition tothose listed below,zlib options may bepassed in to the options object orbrotli options.
Type:Number
Default:zlib.constants.Z_DEFAULT_CHUNK, or16384.
SeeNode.js documentationregarding the usage.
Type:Function
A function to decide if the response should be considered for compression.This function is called asfilter(req, res) and is expected to returntrue to consider the response for compression, orfalse to not compressthe response.
The default filter function uses thecompressiblemodule to determine ifres.getHeader('Content-Type') is compressible.
Type:Number
Default:zlib.constants.Z_DEFAULT_COMPRESSION, or-1
The level of zlib compression to apply to responses. A higher level will resultin better compression, but will take longer to complete. A lower level willresult in less compression, but will be much faster.
This is an integer in the range of0 (no compression) to9 (maximumcompression). The special value-1 can be used to mean the "defaultcompression level", which is a default compromise between speed andcompression (currently equivalent to level 6).
-1Default compression level (alsozlib.constants.Z_DEFAULT_COMPRESSION).0No compression (alsozlib.constants.Z_NO_COMPRESSION).1Fastest compression (alsozlib.constants.Z_BEST_SPEED).23456(currently whatzlib.constants.Z_DEFAULT_COMPRESSIONpoints to).789Best compression (alsozlib.constants.Z_BEST_COMPRESSION).
Note in the list above,zlib is fromzlib = require('zlib').
Type:Number
Default:zlib.constants.Z_DEFAULT_MEMLEVEL, or8
This specifies how much memory should be allocated for the internal compressionstate and is an integer in the range of1 (minimum level) and9 (maximumlevel).
SeeNode.js documentationregarding the usage.
Type:Object
This specifies the options for configuring Brotli. SeeNode.js documentation for a complete list of available options.
Type:Number
Default:zlib.constants.Z_DEFAULT_STRATEGY
This is used to tune the compression algorithm. This value only affects thecompression ratio, not the correctness of the compressed output, even if itis not set appropriately.
zlib.constants.Z_DEFAULT_STRATEGYUse for normal data.zlib.constants.Z_FILTEREDUse for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat randomdistribution. In this case, the compression algorithm is tuned tocompress them better. The effect is to force more Huffman coding and lessstring matching; it is somewhat intermediate betweenzlib.constants.Z_DEFAULT_STRATEGYandzlib.constants.Z_HUFFMAN_ONLY.zlib.constants.Z_FIXEDUse to prevent the use of dynamic Huffman codes, allowingfor a simpler decoder for special applications.zlib.constants.Z_HUFFMAN_ONLYUse to force Huffman encoding only (no string match).zlib.constants.Z_RLEUse to limit match distances to one (run-length encoding).This is designed to be almost as fast aszlib.constants.Z_HUFFMAN_ONLY, but givebetter compression for PNG image data.
Note in the list above,zlib is fromzlib = require('zlib').
Type:Number orString
Default:1kb
The byte threshold for the response body size before compression is consideredfor the response. This is a number of bytes or any stringaccepted by thebytes module.
Note this is only an advisory setting; if the response size cannot be determinedat the time the response headers are written, then it is assumed the response isover the threshold. To guarantee the response size can be determined, be sureset aContent-Length response header.
Type:Number
Default:zlib.constants.Z_DEFAULT_WINDOWBITS, or15
SeeNode.js documentationregarding the usage.
Type:String
Default:identity
This is the default encoding to use when the client does not specify an encoding in the request'sAccept-Encoding header.
The defaultfilter function. This is used to construct a custom filterfunction that is an extension of the default function.
varcompression=require('compression')varexpress=require('express')varapp=express()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 ares.flush() method to force the partially-compressedresponse to be flushed to the client.
When using this module with express, simplyapp.use the module ashigh as you like. Requests that pass through the middleware will be compressed.
varcompression=require('compression')varexpress=require('express')varapp=express()// compress all responsesapp.use(compression())// add all routes
varcompression=require('compression')({threshold:0})varhttp=require('http')functioncreateServer(fn){returnhttp.createServer(function(req,res){compression(req,res,function(err){if(err){res.statusCode=err.status||500res.end(err.message)return}fn(req,res)})})}varserver=createServer(function(req,res){res.setHeader('Content-Type','text/plain')res.end('hello world!')})server.listen(3000,()=>{console.log('> Listening at http://localhost:3000')})
Because of the nature of compression this module does not work out of the boxwith server-sent events. To compress content, a window of the output needs tobe buffered up in order to get good compression. Typically when using server-sentevents, there are certain block of data that need to reach the client.
You can achieve this by callingres.flush() when you need the data written toactually 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)})})
The Express.js project welcomes all constructive contributions. Contributions take many forms,from code for bug fixes and enhancements, to additions and fixes to documentation, additionaltests, triaging incoming pull requests and issues, and more!
See theContributing Guide for more technical details on contributing.
About
Node.js compression middleware
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.