Node.js 和 Express 中的压缩减少了向用户提供的可下载数据量,通过使用这种压缩,我们可以提高 Node.js 应用程序的性能,因为我们的负载量大大减少。
压缩有两种方法:一种是使用压缩
中间软件直接在您的 Node.js 应用程序中调用,另一种是通过像 NGINX 这样的软件在反向代理级别上使用。
如何设置压缩
要开始在 Node.js 应用程序中使用压缩,您可以在 Node.js 应用程序的主要文件中使用压缩
中间软件. 这将启用 GZIP,这支持不同的压缩方案. 这将使您的 JSON 响应和其他静态文件响应更小。
首先,您需要安装压缩
的 npm 包:
1$ npm i compression --save
然后,您可以在初始化服务器后在应用程序中使用该模块,如同Express.js:
1const compression = require('compression');
2const express = require('express');
3
4const app = express();
5
6// compress all responses
7app.use(compression());
8
9app.get('/', (req, res) => {
10 const animal = 'alligator';
11 // Send a text/html file back with the word 'alligator' repeated 1000 times
12 res.send(animal.repeat(1000));
13});
14
15// ...
在上面的例子中,我们称之为 GET 操作,该操作将发送一个文本/html
文件,其中alligator
字被打印了 1000 次。
如果打开压缩,响应将发送一个标题,该标题表示内容编码:gzip
,而不是只有342B。
压缩的选择
除了默认设置外,您还可以自定义您的压缩以适应您的使用情况. 您可以在选项对象中使用的几个不同的属性. 若要查看可选择的完整属性列表,请参阅压缩
文档。
要添加您的压缩
的选项,您的代码将看起来有点像这样:
1const shouldCompress = (req, res) => {
2 if (req.headers['x-no-compression']) {
3 // don't compress responses if this request header is present
4 return false;
5 }
6
7 // fallback to standard compression
8 return compression.filter(req, res);
9};
10
11app.use(compression({
12 // filter decides if the response should be compressed or not,
13 // based on the `shouldCompress` function above
14 filter: shouldCompress,
15 // threshold is the byte threshold for the response body size
16 // before compression is considered, the default is 1kb
17 threshold: 0
18}));
然后你有它! 确保你使用你的 Node.js 应用程序的压缩
,以保持你的负载尺寸小而快捷!