节点zlib模块不压缩缓冲的字符串或Stream.Readable

时间:2016-10-11 16:14:14

标签: node.js zlib

我正在使用node的sitemap模块,该模块为我的网站生成一个带有sitemap xml的字符串。由于这是一个非常大的站点地图,我想将其压缩发送(例如,作为sitemap.xml.gz)。但是,zlib模块没有压缩它。它可以工作,如果我将它流式传输到服务器中的文件,然后使用此文件来压缩它,但我希望能够直接压缩生成的xml字符串。 这就是我在做的事情:

res.header('Content-Type', 'application/x-gzip');
res.header('Content-Encoding', 'gzip');        
res.header('ContentDisposition',
'attachment;filename="sitemap.xml.gzip"'); 

//testString is used here as an example, the generated sitemap xml will go here
var testString = '<?xml version="1.0" encoding="UTF-8"?>';
var input = Buffer.from(testString, 'utf8');
zlib.gzip(input, function(buferror, data) {
      res.send(data);
});

我也尝试过使用流模块缓冲字符串,并将其通过管道,如下所示:

var s = new stream.Readable();
s._read = function noop() {};
s.push(testString);
s.push(null);
s.pipe(zlib.createGzip()).pipe(res);

但是,我仍然得到相同的结果,一个压缩的sitemap.xml.gzip文件。正如我所提到的,如果我将生成的xml字符串放入服务器中的文件中,并且像这样管道它,我能够使它工作:

var raw = fs.createReadStream('input.txt.gz');
raw.pipe(zlib.createGzip()).pipe(res);

但我想避免这种解决方法。谁能解释我做错了什么?提前致谢!

1 个答案:

答案 0 :(得分:0)

当您使用Content-Encoding: gzip时,您允许浏览器自动解码(/ gunzip)响应内容。

如果您不想这样做,请不要设置该标头(同样,您的ContentDisposition标头错过了连字符,它应该是Content-Disposition)。

相关问题