expressjs / compression

Node.js compression middleware
MIT License
2.77k stars 241 forks source link

does compression support compress the static files? #68

Closed xjmalm closed 8 years ago

xjmalm commented 8 years ago

I'd like to compress the static files like html/client js/css etc, I see some articles say that we can use nginx as the proxy in front of the node js server, does compression also support to do such kind of things? If it supports, how can I debug to make sure it does compress them?

Thanks in advance.

dougwilson commented 8 years ago

Hi! Yes, this module does compress static files. Essentially, this module provides a middleware to Express, Connect, and other similar systems that will compress whatever gets written to the output stream, regardless of the underlying source.

If you are using Express, here is a simple example to compress all your static files:

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

var app = express()

// compress all requests
app.use(compression())

// app.use statements from here on are compressed
// as long as the client requests compression and the
// response is > 1kb

// serve static files
app.use(express.static(__dirname + '/public'))

// listen
app.listen(3000)

If you wanted to debug if compression is working for a particular request, you can use your choice of client that can ask for compressed responses and tell you if they were (this is tricky, and you'll likely have to read the documentation for the tool you are using thoroughly to understand if you are doing it right) or you can use the DEBUG variable and look at the console.

For example, if the above example was saved as app.js, you can run DEBUG=compression node app.js from a bash-like command shell and then make a request to the server like curl http://127.0.0.1:3000/. You'll see no compression: size below threshold, telling you compression is working, but the 404 was not compressed because it was too small.

xjmalm commented 8 years ago

Many thanks dougwilson for your kind help.