压缩中间件
Node.js 压缩中间件。
🌐 Node.js compression middleware.
支持以下压缩编码:
🌐 The following compression codings are supported:
- deflate
- gzip
- br(Brotli)
注意 Brotli 仅自 Node.js 版本 v11.7.0 和 v10.16.0 起受到支持。
安装
🌐 Install
这是一个可以通过npm注册表获取的Node.js模块。安装可以使用npm install命令完成:
🌐 This is a Node.js module available through the
npm registry. Installation is done using the
npm install command:
npm install compressionyarn add compressionpnpm add compressionbun add compressionNote
compression 不包含其自身的 TypeScript 类型定义。如果你使用 TypeScript,还需要作为开发依赖从 DefinitelyTyped 安装社区维护的类型:
npm install --save-dev @types/compressionyarn add --dev @types/compressionpnpm add --save-dev @types/compressionbun add --dev @types/compressionAPI
var compression = require('compression');compression([options])
返回使用给定 options 的压缩中间件。该中间件将尝试压缩所有通过中间件的请求的响应体,基于给定的 options。
🌐 Returns the compression middleware using the given options. The middleware
will attempt to compress response bodies for all requests that traverse through
the middleware, based on the given options.
这个中间件永远不会压缩包含 Cache-Control 头和 no-transform 指令 的响应,因为压缩会改变主体。
🌐 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() 在选项对象中接受这些属性。除了下面列出的属性外,还可以将 zlib 选项或 brotli 选项传递到选项对象中。
chunkSize
类型:Number
默认值:zlib.constants.Z_DEFAULT_CHUNK,或 16384。
🌐 Type: Number
Default: zlib.constants.Z_DEFAULT_CHUNK, or 16384.
请参阅 Node.js 文档 了解用法。
🌐 See Node.js documentation regarding the usage.
filter
类型:Function
🌐 Type: Function
一个用于决定响应是否应考虑压缩的函数。该函数被调用为 filter(req, res),预计返回 true 以考虑对响应进行压缩,或返回 false 以不压缩响应。
🌐 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.
默认的过滤函数使用 compressible 模块来确定 res.getHeader('Content-Type') 是否可压缩。
🌐 The default filter function uses the compressible
module to determine if res.getHeader('Content-Type') is compressible.
level
类型:Number
默认值:zlib.constants.Z_DEFAULT_COMPRESSION,或 -1
🌐 Type: Number
Default: zlib.constants.Z_DEFAULT_COMPRESSION, or -1
对响应应用的 zlib 压缩级别。较高的级别将产生更好的压缩效果,但完成时间更长。较低的级别压缩效果较差,但速度会更快。
🌐 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.
这是 0(无压缩)到 9(最大压缩)范围内的一个整数。特殊值 -1 可用于表示“默认压缩等级”,即速度和压缩率之间的默认折中(目前相当于等级 6)。
🌐 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默认压缩级别(也可为zlib.constants.Z_DEFAULT_COMPRESSION)。0无压缩(也称zlib.constants.Z_NO_COMPRESSION)。1最快的压缩(也叫zlib.constants.Z_BEST_SPEED)。23456(当前zlib.constants.Z_DEFAULT_COMPRESSION指向的内容)。789最佳压缩(也称zlib.constants.Z_BEST_COMPRESSION)。
注意 在上面的列表中,zlib 来自 zlib = require('zlib')。
memLevel
类型:Number
默认值:zlib.constants.Z_DEFAULT_MEMLEVEL,或 8
🌐 Type: Number
Default: zlib.constants.Z_DEFAULT_MEMLEVEL, or 8
这指定了应为内部压缩状态分配多少内存,并且是一个介于 1(最低级别) 和 9(最高级别)之间的整数。
🌐 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).
请参阅 Node.js 文档 了解用法。
🌐 See Node.js documentation regarding the usage.
brotli
类型:Object
🌐 Type: Object
这指定了配置 Brotli 的选项。有关可用选项的完整列表,请参阅 Node.js 文档。
🌐 This specifies the options for configuring Brotli. See Node.js documentation for a complete list of available options.
strategy
类型:Number
默认:zlib.constants.Z_DEFAULT_STRATEGY
🌐 Type: Number
Default: zlib.constants.Z_DEFAULT_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.constants.Z_DEFAULT_STRATEGY用于普通数据。zlib.constants.Z_FILTERED用于滤波器(或预测器)生成的数据。滤波后的数据主要由较小的数值组成,具有一定随机分布。在这种情况下,压缩算法经过调整以更好地压缩这些数据。其效果是增加霍夫曼编码的使用,减少字符串匹配的使用;在zlib.constants.Z_DEFAULT_STRATEGY和zlib.constants.Z_HUFFMAN_ONLY之间具有一定的中间性质。zlib.constants.Z_FIXED用于防止使用动态哈夫曼编码,从而允许为特殊应用提供更简单的解码器。zlib.constants.Z_HUFFMAN_ONLY仅用于强制使用 Huffman 编码(不进行字符串匹配)。zlib.constants.Z_RLE用于将匹配距离限制为 1(行程长度编码)。它的设计目标是几乎和zlib.constants.Z_HUFFMAN_ONLY一样快速,但能够为 PNG 图片数据提供更好的压缩效果。
注意 在上面的列表中,zlib 来自 zlib = require('zlib')。
threshold
类型:Number 或 String
默认:1kb
🌐 Type: Number or String
Default: 1kb
在考虑响应的压缩之前,响应主体大小的字节阈值。这是字节数或任何被bytes模块接受的字符串。
🌐 The byte threshold for the response body size before compression is considered for the response. This is a number of bytes or any string accepted by the bytes module.
注意 这只是一个建议性设置;如果在写入响应头时无法确定响应大小,则假定响应超过阈值。要确保可以确定响应大小,请务必设置一个 Content-Length 响应头。
windowBits
类型:Number
默认值:zlib.constants.Z_DEFAULT_WINDOWBITS,或 15
🌐 Type: Number
Default: zlib.constants.Z_DEFAULT_WINDOWBITS, or 15
请参阅 Node.js 文档 了解用法。
🌐 See Node.js documentation regarding the usage.
enforceEncoding
类型: String
默认: identity
🌐 Type: String
Default: identity
当客户端未在请求的 Accept-Encoding 头中指定编码时,这是默认使用的编码。
🌐 This is the default encoding to use when the client does not specify an encoding in the request’s Accept-Encoding header.
.filter
默认的 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
此模块添加了一个 res.flush() 方法,用于强制将部分压缩的响应刷新到客户端。
🌐 This module adds a res.flush() method to force the partially-compressed
response to be flushed to the client.
例子
🌐 Examples
express
在将此模块与 Express 一起使用时,只需将模块 app.use 至你希望的高度。通过中间件的请求将被压缩。
🌐 When using this module with express, 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 responsesapp.use(compression());
// add all routesNode.js HTTP 服务器
🌐 Node.js HTTP server
var compression = require('compression')({ threshold: 0 });var http = require('http');
function createServer(fn) { return http.createServer(function (req, res) { compression(req, res, function (err) { if (err) { res.statusCode = err.status || 500; res.end(err.message); return; }
fn(req, res); }); });}
var server = 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 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.
当你需要将数据写入并实际传输到客户端时,可以通过调用 res.flush() 来实现这一点。
🌐 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 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 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); });});贡献
🌐 Contributing
Express.js 项目欢迎所有建设性的贡献。贡献有多种形式,从用于修复错误和增强功能的代码,到对文档的新增和修复、额外的测试、整理收到的拉取请求和问题等等!
🌐 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, additional tests, triaging incoming pull requests and issues, and more!
有关更多贡献的技术细节,请参阅贡献指南。
🌐 See the Contributing Guide for more technical details on contributing.
许可证
🌐 License