Do not forget to use Gzip for Express.js

转载自: http://inspiredjw.com/do-not-forget-to-use-gzip-for-express/

 

When a gzip compatible browser requests to a web server, web server can compress the response to the browser back and the browser can decompress the response and finally the browser get the original response.

If the server does not take care of gzip compression, the original size of data is passed which takes longer time than using gzip because it is sending bigger data!

For Express 2.x, I used to use Gzippo which is no longer working for recent version of Node.js and Express.

Since Express 3.x, the express.compress() is available with Express itself.

 

How to apply Gzip?

In your main file something like app.js or index.js, you have bunch of app.use.

app.use(express.json()); app.use(express.urlencoded()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser());

 

Add express.compress() at the very top would enable the gzip compression on your web server.

app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser());

 

For Express 4.x

You need to install middlewares separately for Express 4.x.

var compress = require('compression'); app.use(compress());

 

Check your website

After applying gzip on your web server, you should check your website whether it is using gzip or not.

Go to GzipTest and enter your site url.

If you see this, you are successfully applied gzip compression on your website!

If you have some questions or want to say something about this post, you can comment below :)

你可能感兴趣的:(nodejs)