20

我试图用 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);
4

1 回答 1

43

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

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

简化是不使用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);

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

同样,如果您需要传递 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);
});
于 2013-02-08T18:00:35.367 回答