How to add headers to static gzip file in express/

2019-05-23 12:03发布

问题:

I have some files, from a Unity build, that I am unable to add headers to. They have extensions jsgz, memgz and datagz. They are located in my public folder within my NodeJs project. I am using Express 4 and have set up Compression but I believe that this only compresses existing files for transmission, and does not handle files that are already compressed. I have tried using app.get to add headers but it doesn't seem to work:

app.get('/blah/unitymodels/Release/widget.js', function(req, res, next) {
  ... Check ['accept-encoding'] ...
  if (acceptsGzip) {
      var gzippedPath = req.url + 'gz';
      res.sendFile(gzippedPath, {
          root: './public',
          headers: {
              'Content-Encoding': 'gzip',
              'Content-Type': 'application/javascript'
          }
  }
...

I have tried setting the headers like this, by using res.set and by setting them first then letting the next() call handle the response but whenever I get the file back it is just the gzip file without the extra headers and the browser does not understand it. The approaches I have tried do add other headers ('wibble', 'x-timestamp', etc) so I assume that something else is intercepting these specific ones. How am I able to return these gzipped files so that the browser understands them?

回答1:

You can use express-static-gzip as Express middleware as shown below:

/* here serves gzipped static files */
app.use('/my_static/zipped/', expressStaticGzip('my_static/zipped/', {
    customCompressions: [{
        encodingName: "gzip",
        fileExtension: "gz"
    }]
}));

/* here serves other static files */
app.use('/my_static', express.static('my_static'));