how to create a simple node server that compresses

2019-05-15 23:37发布

问题:

I've been on this for hours..

the first thing i did was follow this tutorial which had this code:

var express = require('express');
var app = express();

// New call to compress content
app.use(express.compress());    
app.use(express.static(__dirname + '/public'));
app.listen(3333);

naturally the code was outdated.. and I got this error:

Error: Most middleware (like compress) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

so i updated the code to:

var express = require('express');
var app = express();
var compression = require('compression')

app.use(compression());
app.use(express.static(__dirname + '/_public' ));    

app.listen(3333);

which worked fine.. but I saw no evidence of compression (how do i know? by viewing the chrome dev tools response headers:

it doesn't have the gzip content-encoding header like the one in the tutorial:

So tried using the zlib library instead:

var express = require('express');
var app     = express();
var maxAge  = 31557600000;
var zlib = require('zlib');
app.use(express.static(__dirname + '/_public' ));

app.get('/*', function(req,res)
{
  res.sendFile(__dirname + '/_public/index.html').pipe(zlib.createGunzip()).pipe(output);
});

app.listen(3333);

but that didn't work out either.. and i'm pretty much left bald at this point.. any help?

p.s. the compression docs say you can provide zlib options, but fail to provide any examples/explanation.


update: the question has been fully answered and marked as such (i hate moving target questions).. but I can't help but asking: and so how can you verify how much of your original payload got trimmed as a result of gzip compression? Since naturally the compressing/decompressing happens behinds the scenes and as such chrome dev tools will report the original size of the file in its networking tab:

回答1:

I believe your setup, using the compression module, is correct. I just don't think it compresses the files during development.

Try setting the NODE_ENV to "production", e.g.

$ NODE_ENV="production" $ node server.js

EDIT To your follow up question.

Essentially what you are seeing in Chrome Dev Tools is the result of the compressed gzip compression. This answer describes it better then I can:

"Size" is the number of bytes on the wire, and "content" is the actual size of the resource

gzip compression reduces the "on the wire" size of the resource.

So, in your example, there will be 450 KB for the end user to download.



回答2:

zlib.createGunzip() is for decompressing.

I think that using headers and streams works.

app.get('/', function(req,res){
  res.writeHead(200, {
  'Content-Encoding': 'gzip' });
 fs.createReadStream('_public/index.html').pipe(zlib.createGzip()).pipe(res);
});


回答3:

Also, specify threshold value for small files compression (under 1kb) :

app.use(compression({ threshold: 0 }));