Nodejs 使用 zlib 以 gzip 格式发送数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14778239/
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 17:07:35  来源:igfitidea点击:

Nodejs send data in gzip using zlib

node.jsgzip

提问by friction

I tried to send the text in gzip, but I don't know how. In the examplesthe code uses fs, but I don't want to send a text file, just a string.

我试图用 gzip 发送文本,但我不知道如何发送。在示例中,代码使用 fs,但我不想发送文本文件,只是一个字符串。

const zlib = require('zlib');
const http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    const text = "Hello World!";
    res.end(text);

}).listen(80);

回答by Joachim Isaksson

You're half way there. I can heartily agree that the documentation isn't quite up to snuff on how to do this;

你已经成功了一半。我非常同意文档并不能完全说明如何做到这一点;

const zlib = require('zlib');
const http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    const text = "Hello World!";
    const buf = new Buffer(text, 'utf-8');   // Choose encoding for the string.
    zlib.gzip(buf, function (_, result) {  // The callback will give you the 
        res.end(result);                     // result, so just send it.
    });
}).listen(80);

A simplification would be not to use the Buffer;

一个简化是不使用Buffer;

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    const text = "Hello World!";
    zlib.gzip(text, function (_, result) {  // The callback will give you the 
      res.end(result);                     // result, so just send it.
    });
}).listen(80);

...and it seems to send UTF-8 by default. However, I personally prefer to walk on the safe side when there is no default behavior that makes more sense than others and I can't immediately confirm it with documentation.

...它似乎默认发送 UTF-8。但是,当没有比其他人更有意义的默认行为并且我无法立即用文档确认时,我个人更喜欢安全地行走。

Similarly, in case you need to pass a JSON object instead:

同样,如果您需要传递一个 JSON 对象:

const data = {'hello':'swateek!'}

res.writeHead(200, {'Content-Type': 'application/json', 'Content-Encoding': 'gzip'});
const buf = new Buffer(JSON.stringify(data), 'utf-8');
zlib.gzip(buf, function (_, result) {
    res.end(result);
});