Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Node.js compression middleware

License

NotificationsYou must be signed in to change notification settings

expressjs/compression

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

NPM VersionNPM DownloadsBuild StatusOpenSSF Scorecard BadgeFunding

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.

Install

This is aNode.js module available through thenpm registry. Installation is done using thenpm install command:

$ npm install compression

API

varcompression=require('compression')

compression([options])

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.

Options

compression() accepts these properties in the options object. In addition tothose listed below,zlib options may bepassed in to the options object orbrotli options.

chunkSize

Type:Number
Default:zlib.constants.Z_DEFAULT_CHUNK, or16384.

SeeNode.js documentationregarding the usage.

filter

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.

level

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).

  • -1 Default compression level (alsozlib.constants.Z_DEFAULT_COMPRESSION).
  • 0 No compression (alsozlib.constants.Z_NO_COMPRESSION).
  • 1 Fastest compression (alsozlib.constants.Z_BEST_SPEED).
  • 2
  • 3
  • 4
  • 5
  • 6 (currently whatzlib.constants.Z_DEFAULT_COMPRESSION points to).
  • 7
  • 8
  • 9 Best compression (alsozlib.constants.Z_BEST_COMPRESSION).

Note in the list above,zlib is fromzlib = require('zlib').

memLevel

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.

brotli

Type:Object

This specifies the options for configuring Brotli. SeeNode.js documentation for a complete list of available options.

strategy

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_STRATEGY Use for normal data.
  • zlib.constants.Z_FILTERED Use 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_FIXED Use to prevent the use of dynamic Huffman codes, allowingfor a simpler decoder for special applications.
  • zlib.constants.Z_HUFFMAN_ONLY Use to force Huffman encoding only (no string match).
  • zlib.constants.Z_RLE Use 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').

threshold

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.

windowBits

Type:Number
Default:zlib.constants.Z_DEFAULT_WINDOWBITS, or15

SeeNode.js documentationregarding the usage.

enforceEncoding

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.

.filter

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)}

res.flush

This module adds ares.flush() method to force the partially-compressedresponse to be flushed to the client.

Examples

express

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

Node.js HTTP server

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')})

Server-Sent Events

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)})})

Contributing

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.

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp