How to create a simple node server that gzips static files
I was at this hour.
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 is 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 didn't see evidence of compression (how do I know?) by looking at the chrome-dev-tools answer headers:
it doesn't have a gzip header content-encoding
like the one given in the tutorial:
So, tried instead of zlib :
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 either. And this time I was almost bald. Any help?
ps the docs compression says you can provide zlib options, but cannot provide any examples / explanations.
update: the question has been fully answered and marked as such (I hate moving target questions) .. but I can't help but ask: and so how can you check how much of your original payload has been truncated as a result of gzip compression? Since, naturally, the compression / decompression happens behind the scenes, and therefore such chrome tools will report the original file size on their network tab:
source to share
I believe your setup using the module is compression
correct. I just don't think it compresses files during development.
Try installing NODE_ENV
in "production" like
$ NODE_ENV="production"
$ node server.js
EDIT To your next question.
Basically, what you see in Chrome Dev Tools is the result of the compressed gzip compression. This answer describes it better than I can:
"Size" is the number of bytes on the wire and "content" is the actual size of the resource
gzip compression reduces the size of the "per wire" resource.
So in your example, 450KB will be downloaded for the end user.
source to share