简体   繁体   中英

Express with node.js not compressing jpeg images

I am (a beginner and ) trying to serve gzipped jpegs with node.js and Express framework. I have the images in /public folder. My code looks like:

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

Am I missing something? On the Chrome debugger, with the cache disabled (ensure that HTTP response code is 200) the content-encoding: gzip header is not found in the response.

Any leads as to what I am missing?

Disclaimer: you really shouldn't attempt to gzip images. You seem to have a good reason for this, but I'm writing this for future readers :).

If you take a look at the compress middleware source code , you'll find this:

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

By default, only text files are compressed. This is logical, since binary files like images are already compressed.

Fortunately, you can pass your own:

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

This should compress everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM