【问题标题】:Express with node.js not compressing jpeg images使用 node.js 表示不压缩 jpeg 图像
【发布时间】:2013-11-26 01:14:02
【问题描述】:

我(一个初学者)正在尝试使用 node.js 和 Express 框架来提供 gzipped jpegs。我在 /public 文件夹中有图像。我的代码如下:

// require the express module
var express = require('express');
var app = express();
app.use(express.logger());

//compress static content
app.use(express.compress());

// GET verbs
app.get('/', function(request, response) {
  response.send('Hello World!');
});


// GET /public/*
app.use(express.static(__dirname + '/public'));

// Start the app on port 8080 if PORT not set
var port = process.env.PORT || 8080;
app.listen(port, function() {
  console.log("Listening on " + port);
});

我错过了什么吗?在 Chrome 调试器上,禁用缓存(确保 HTTP 响应代码为 200)后,在响应中找不到 content-encoding: gzip 标头。

关于我缺少什么的任何线索?

【问题讨论】:

  • 文本资源正在工作(gzip'd 标题显示在响应中)。另外,为什么我需要 gzip'd jpegs 是为了测试来自网页的 jpeg 带有压缩标头时的边缘情况。
  • 如果您希望节省一些带宽,另一件需要考虑的事情是自定义静态图像上的缓存控制标头

标签: javascript node.js express gzip


【解决方案1】:

免责声明:您真的不应该尝试 gzip 图像。你似乎有一个很好的理由,但我正在为未来的读者写这篇文章:)。

如果您查看压缩中间件source code,您会发现:

exports.filter = function(req, res){
  return /json|text|javascript|dart|image\/svg\+xml|application\/x-font-ttf|application\/vnd\.ms-opentype|application\/vnd\.ms-fontobject/.test(res.getHeader('Content-Type'));
};

默认情况下,仅压缩文本文件。这是合乎逻辑的,因为像图像这样的二进制文件已经被压缩了。

幸运的是,你可以通过自己的:

express.compress({
  filter: function (req, res) {
    return true;
  })
});

这应该会压缩所有内容。

【讨论】:

  • “你真的不应该尝试压缩图像” - 你能解释一下原因吗?
猜你喜欢
  • 2013-02-22
  • 1970-01-01
  • 2010-09-22
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2012-05-16
  • 2016-04-30
相关资源
最近更新 更多