Node.js: Gzip compression?

2019-01-07 05:47发布

Am I wrong in finding that Node.js does no gzip compression and there are no modules out there to perform gzip compression? How can anyone use a web server that has no compression? What am I missing here? Should I try to—gasp—port the algorithm to JavaScript for server-side use?

14条回答
Luminary・发光体
2楼-- · 2019-01-07 05:52

Although you can gzip using a reverse proxy such as nginx, lighttpd or in varnish. It can be beneficial to have most http optimisations such as gzipping at the application level so that you can have a much granular approach on what asset's to gzip.

I have actually created my own gzip module for expressjs / connect called gzippo https://github.com/tomgco/gzippo although new it does do the job. Plus it uses node-compress instead of spawning the unix gzip command.

查看更多
ら.Afraid
3楼-- · 2019-01-07 05:53

As of today, epxress.compress() seems to be doing a brilliant job of this.

in any express app just call this.use(express.compress()); I'm running locomotive on top of express personally and this is working beautifully. I can't speak to any other libraries or frameworks built on top of express but as long as they honour full stack transparency you should be fine.

查看更多
该账号已被封号
4楼-- · 2019-01-07 05:54

Generally speaking, for a production web application, you will want to put your node.js app behind a lightweight reverse proxy such as nginx or lighttpd. Among the many benefits of this setup, you can configure the reverse proxy to do http compression or even tls compression, without having to change your application source code.

查看更多
Ridiculous、
5楼-- · 2019-01-07 05:54

How about this?

node-compress
A streaming compression / gzip module for node.js
To install, ensure that you have libz installed, and run:
node-waf configure
node-waf build
This will put the compress.node binary module in build/default.
...

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-07 05:55

For compressing the file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt').pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));
console.log("File Compressed.");

For decompressing the same file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("File Decompressed.");
查看更多
beautiful°
7楼-- · 2019-01-07 05:58

1- Install compression

npm install compression

2- Use it

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

var app = express()
app.use(compression())

compression on Github

查看更多
登录 后发表回答