abbood abbood - 4 months ago 12
Node.js Question

how to create a simple node server that compresses static files using gzip

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.static(__dirname + '/public'));

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

so i updated the code to:

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

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


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

enter image description here

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

enter image description here

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


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.

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:

enter image description here


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.