Node.js使用zlib以gzip发送数据 [英] Nodejs send data in gzip using zlib

查看:175
本文介绍了Node.js使用zlib以gzip发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

您已经到了一半.我可以衷心地同意,该文档还不足以使您了解如何执行此操作;

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

一个简化就是不使用Buffer;

A simplification would be not to use the 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.但是,当没有默认行为比其他行为更有意义并且我无法立即通过文档进行确认时,我个人宁愿走在安全方面.

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

类似地,如果您需要传递一个JSON对象来代替:

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

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

这篇关于Node.js使用zlib以gzip发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆