Node.js:Gzip 压缩?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3894794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:42:00  来源:igfitidea点击:

Node.js: Gzip compression?

compressiongzipnode.js

提问by SnickersAreMyFave

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?

我发现 Node.js 没有 gzip 压缩并且没有模块可以执行 gzip 压缩,我错了吗?任何人都如何使用没有压缩的网络服务器?我在这里缺少什么?我是否应该尝试将算法移植到 JavaScript 以供服务器端使用?

回答by hughsk

Node v0.6.x has a stable zlib modulein core now - there are some examples on how to use it server-side in the docs too.

Node v0.6.x现在在核心中有一个稳定的zlib 模块- 在文档中也有一些关于如何在服务器端使用它的示例。

An example (taken from the docs):

一个例子(取自文档):

// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
  var raw = fs.createReadStream('index.html');
  var acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';
  }

  // Note: this is not a conformant accept-encoding parser.
  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  if (acceptEncoding.match(/\bdeflate\b/)) {
    response.writeHead(200, { 'content-encoding': 'deflate' });
    raw.pipe(zlib.createDeflate()).pipe(response);
  } else if (acceptEncoding.match(/\bgzip\b/)) {
    response.writeHead(200, { 'content-encoding': 'gzip' });
    raw.pipe(zlib.createGzip()).pipe(response);
  } else {
    response.writeHead(200, {});
    raw.pipe(response);
  }
}).listen(1337);

回答by Milimetric

If you're using Express, then you can use its compress method as part of the configuration:

如果您使用Express,那么您可以使用其 compress 方法作为配置的一部分:

var express = require('express');
var app = express.createServer();
app.use(express.compress());

And you can find more on compress here: http://expressjs.com/api.html#compress

您可以在此处找到有关 compress 的更多信息:http: //expressjs.com/api.html#compress

And if you're not using Express... Why not, man?! :)

如果你不使用Express......为什么不呢,伙计?!:)

NOTE: (thanks to @ankitjaininfo) This middleware should be one of the first you "use" to ensure all responses are compressed. Ensure that this is above your routes and static handler (eg. how I have it above).

注意:(感谢@ankitjaininfo)这个中间件应该是您“使用”的第一个中间件,以确保所有响应都被压缩。确保这在您的路由和静态处理程序之上(例如我在上面的方式)。

NOTE: (thanks to @ciro-costa) Since express 4.0, the express.compressmiddleware is deprecated. It was inherited from connect 3.0 and express no longer includes connect 3.0. Check Express Compressionfor getting the middleware.

注意:(感谢@ciro-costa)从 express 4.0 开始,express.compress不推荐使用中间件。它继承自 connect 3.0,express 不再包含 connect 3.0。检查Express Compression以获取中间件。

回答by CoyBit

1- Install compression

1-安装压缩

npm install compression

2- Use it

2-使用它

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

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

compression on Github

Github 上的压缩

回答by yfeldblum

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.

一般来说,对于生产 Web 应用程序,您需要将 node.js 应用程序置于轻量级反向代理(如 nginx 或 lighttpd)之后。在此设置的众多好处中,您可以将反向代理配置为进行 http 压缩甚至 tls 压缩,而无需更改应用程序源代码。

回答by tomgco

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.

尽管您可以使用反向代理(例如 nginx、lighttpd 或清漆)进行 gzip。在应用程序级别进行大多数 http 优化(例如 gzip)是有益的,这样您就可以对要 gzip 的资产有更精细的方法。

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

我实际上已经为 expressjs/connect 创建了我自己的 gzip 模块,称为 gzippo https://github.com/tomgco/gzippo虽然它是新的,但它确实可以完成这项工作。此外,它使用 node-compress 而不是产生 unix gzip 命令。

回答by B T

Even if you're not using express, you can still use their middleware. The compression moduleis what I'm using:

即使您不使用 express,您仍然可以使用他们的中间件。该压缩模块是我使用的是什么:

var http = require('http')
var fs = require('fs')
var compress = require("compression")
http.createServer(function(request, response) {
  var noop = function(){}, useDefaultOptions = {}
  compress(useDefaultOptions)(request,response,noop) // mutates the response object

  response.writeHead(200)
  fs.createReadStream('index.html').pipe(response)
}).listen(1337)

回答by Krish Hymanman

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

回答by cavalcade

While as others have right pointed out using a front end webserver such as nginxcan handle this implicitly, another option, is to use nodejitsu'sexcellent node-http-proxyto serve up your assets.

正如其他人所指出的那样,使用前端网络服务器(例如nginx可以隐式处理此问题),另一种选择是使用nodejitsu出色的node-http-proxy来为您的资产提供服务。

eg:

例如:

httpProxy.createServer(
 require('connect-gzip').gzip(),
 9000, 'localhost'
).listen(8000);

This example demonstrates support for gzip compression through the use of connect middlewaremodule: connect-gzip.

此示例演示了通过使用连接中间件模块对 gzip 压缩的支持:connect-gzip.

回答by Shay Erlichmen

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.
...

node-compress
一个用于 node.js 的流压缩/gzip 模块
要安装,请确保你已经安装了 libz,然后运行:
node-waf configure
node-waf build
这会将 compress.node 二进制模块放在 build/default 中。
...

回答by Sudhanshu

It's been a few good days with node, and you're right to say that you can't create a webserver without gzip.

使用 node 已经好几天了,您说没有 gzip 就无法创建网络服务器是正确的。

There are quite a lot options given on the modules page on the Node.js Wiki. I tried out most of them, but this is the one which I'm finally using -

Node.js Wiki 的模块页面上提供了很多选项。我尝试了其中的大部分,但这是我最终使用的一个 -

https://github.com/donnerHyman13589/node.gzip

https://github.com/donnerHyman13589/node.gzip

v1.0 is also out and it has been quite stable so far.

v1.0 也出来了,到目前为止它已经相当稳定了。