Nodejs使用zlib以gzip发送数据

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

var zlib = require('zlib'); var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'}); var text = "Hello World!"; res.end(text); }).listen(80); 

你是中途的一半。 我可以衷心地同意,这个文件不太适合如何做到;

 var zlib = require('zlib'); var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'}); var text = "Hello World!"; var 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'}); var 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对象:

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