Nodejs使用zlib以gzip发送数据

fri*_*ion 15 gzip node.js

我试着用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);
Run Code Online (Sandbox Code Playgroud)

Joa*_*son 35

你在那里的一半.我可以衷心地同意,这些文件并不完全取决于如何做到这一点;

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);
Run Code Online (Sandbox Code Playgroud)

简化就是不使用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);
Run Code Online (Sandbox Code Playgroud)

......它似乎默认发送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);
});
Run Code Online (Sandbox Code Playgroud)

  • 作为抬头,在将字符串转换为缓冲区而不是"新缓冲区"时,应使用"Buffer.from".`new Buffer`已被弃用.https://nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding (3认同)