• Stars
    star
    2,722
  • Rank 16,035 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Node.js compression middleware

compression

NPM Version NPM Downloads Build Status Test Coverage

Node.js compression middleware.

The following compression codings are supported:

  • deflate
  • gzip

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install compression

API

var compression = require('compression')

compression([options])

Returns the compression middleware using the given options. The middleware will attempt to compress response bodies for all request that traverse through the middleware, based on the given options.

This middleware will never compress responses that include a Cache-Control header with the no-transform directive, as compressing will transform the body.

Options

compression() accepts these properties in the options object. In addition to those listed below, zlib options may be passed in to the options object.

chunkSize

The default value is zlib.Z_DEFAULT_CHUNK, or 16384.

See Node.js documentation regarding the usage.

filter

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.

level

The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.

This is an integer in the range of 0 (no compression) to 9 (maximum compression). The special value -1 can be used to mean the "default compression level", which is a default compromise between speed and compression (currently equivalent to level 6).

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

The default value is zlib.Z_DEFAULT_COMPRESSION, or -1.

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

memLevel

This specifies how much memory should be allocated for the internal compression state and is an integer in the range of 1 (minimum level) and 9 (maximum level).

The default value is zlib.Z_DEFAULT_MEMLEVEL, or 8.

See Node.js documentation regarding the usage.

strategy

This is used to tune the compression algorithm. This value only affects the compression ratio, not the correctness of the compressed output, even if it is not set appropriately.

  • zlib.Z_DEFAULT_STRATEGY Use for normal data.
  • zlib.Z_FILTERED Use for data produced by a filter (or predictor). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect is to force more Huffman coding and less string matching; it is somewhat intermediate between zlib.Z_DEFAULT_STRATEGY and zlib.Z_HUFFMAN_ONLY.
  • zlib.Z_FIXED Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
  • zlib.Z_HUFFMAN_ONLY Use to force Huffman encoding only (no string match).
  • zlib.Z_RLE Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as zlib.Z_HUFFMAN_ONLY, but give better compression for PNG image data.

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

threshold

The byte threshold for the response body size before compression is considered for the response, defaults to 1kb. This is a number of bytes or any string accepted by the bytes module.

Note this is only an advisory setting; if the response size cannot be determined at the time the response headers are written, then it is assumed the response is over the threshold. To guarantee the response size can be determined, be sure set a Content-Length response header.

windowBits

The default value is zlib.Z_DEFAULT_WINDOWBITS, or 15.

See Node.js documentation regarding the usage.

.filter

The default filter function. This is used to construct a custom filter function that is an extension of the default function.

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

res.flush

This module adds a res.flush() method to force the partially-compressed response to be flushed to the client.

Examples

express/connect

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.

var compression = require('compression')
var express = require('express')

var app = express()

// compress all responses
app.use(compression())

// add all routes

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

// compress responses
app.use(compression())

// server-sent event stream
app.get('/events', function (req, res) {
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')

  // send a ping approx every 2 seconds
  var timer = setInterval(function () {
    res.write('data: ping\n\n')

    // !!! this is the important part
    res.flush()
  }, 2000)

  res.on('close', function () {
    clearInterval(timer)
  })
})

License

MIT

More Repositories

1

express

Fast, unopinionated, minimalist web framework for node.
JavaScript
63,539
star
2

multer

Node.js middleware for handling `multipart/form-data`.
JavaScript
11,285
star
3

morgan

HTTP request logger middleware for node.js
JavaScript
7,790
star
4

session

Simple session middleware for Express
JavaScript
6,163
star
5

cors

Node.js CORS middleware
JavaScript
5,961
star
6

body-parser

Node.js body parsing middleware
JavaScript
5,376
star
7

expressjs.com

HTML
5,138
star
8

csurf

CSRF token middleware
2,299
star
9

cookie-parser

Parse HTTP request cookies
JavaScript
1,907
star
10

generator

Express' application generator
JavaScript
1,803
star
11

serve-static

Serve static files
JavaScript
1,368
star
12

cookie-session

Simple cookie-based session middleware
JavaScript
1,104
star
13

vhost

virtual domain hosting
JavaScript
758
star
14

serve-favicon

favicon serving middleware
JavaScript
620
star
15

method-override

Override HTTP verbs.
JavaScript
614
star
16

response-time

Response time header for node.js
JavaScript
458
star
17

serve-index

Serve directory listings
JavaScript
435
star
18

errorhandler

Development-only error handler middleware
JavaScript
423
star
19

express-paginate

Paginate middleware
JavaScript
417
star
20

connect-multiparty

connect middleware for multiparty
JavaScript
347
star
21

express-namespace

Adds namespaced routing capabilities to Express
JavaScript
345
star
22

timeout

Request timeout middleware for Connect/Express
JavaScript
312
star
23

express-expose

Expose raw js, objects, and functions to the client-side (awesome for sharing utils, settings, current user data etc)
JavaScript
299
star
24

basic-auth-connect

Basic auth middleware for node and connect
JavaScript
129
star
25

domain-middleware

`uncaughtException` middleware for connect, base on `domain` module.
JavaScript
101
star
26

api-error-handler

Express error handlers for JSON APIs
JavaScript
100
star
27

flash

JavaScript
92
star
28

restful-router

Simple RESTful url router.
JavaScript
86
star
29

urlrouter

http url router, `connect` missing router middleware
JavaScript
59
star
30

discussions

Public discussions for the Express.js organization
55
star
31

vhostess

virtual host sub-domain mapping
JavaScript
24
star
32

connect-markdown

Auto convert markdown to html for connect.
JavaScript
20
star
33

expressjs.github.io

16
star
34

connect-rid

connect request id middleware
JavaScript
10
star
35

routification

DEPRECATED
JavaScript
10
star
36

mime-extended

DEPRECATED - Please use mime-types instead.
JavaScript
7
star
37

statusboard

A project status board for the Express community
6
star
38

.github

5
star
39

set-type

DEPRECATED - Please use mime-types instead.
JavaScript
5
star
40

security-wg

Express.js Security Working Group
4
star
41

Admin

Admin repository for the Express Organization, including pillarjs and jshttp
2
star