【问题标题】:Nodejs send data in gzip using zlibNodejs 使用 zlib 在 gzip 中发送数据
【发布时间】:2013-01-24 13:17:07
【问题描述】:

我尝试使用 gzip 发送文本,但我不知道如何发送。在examples 中,代码使用了 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);

【问题讨论】:

    标签: node.js gzip


    【解决方案1】:

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

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

    【讨论】:

    • _的值在回调中代表什么?我在想可能是一个错误,但找不到它的记录...
    • @cprcrack 这只是回调的未使用参数。 _ 作为变量/参数名称是有效的,我将其用作标记,这使得(对我而言)它没有被使用非常明显。
    • 我明白了,但仍然想知道回调调用者为什么使用该参数以及它是否有时会被使用/有用。
    • @cprcrack 在这种情况下忽略的参数是error,也就是说,如果gzip 压缩缓冲区失败,你会得到错误传回那里。所有 zlib convenience methods 将(错误,结果)作为参数传回回调。
    • 请注意,将字符串转换为缓冲区时应使用Buffer.from 而不是new Buffernew Buffer 已被弃用。 nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多