如何gzip通过pipe道readStream传递的内容

我目前正在开发一个项目,要求在将内容发送回浏览器之前将其内容进行gZip编辑。

我目前正在使用一个简单的阅读stream和pipe道数据的请求的响应,但我不知道最好的方式来gzip内容没有阻止请求

发送数据的行是:

require('fs').createReadStream(self.staticPath + Request.url).pipe(Response); 

看到下面的类是静态处理程序对象:

 (function(){ var StaticFeeder = function() { this.staticPath = process.cwd() + '/application/static'; this.contentTypes = require('./contenttypes') } StaticFeeder.prototype.handle = function(Request,Response,callback) { var self = this; if(Request.url == '/') { return false; } if(Request.url.indexOf('../') > -1) { return false; } require('path').exists(this.staticPath + Request.url,function(isthere){ /* * If no file exists, pass back to the main handler and return * */ if(isthere === false) { callback(false); return; } /* * Get the extention if possible * */ var ext = require('path').extname(Request.url).replace('.','') /* * Get the Content-Type * */ var ctype = self.contentTypes[ext] !== undefined ? self.contentTypes[ext] : 'application/octet-stream'; /* * Send the Content-Type * */ Response.setHeader('Content-Type',ctype); /* * Create a readable stream and send the file * */ require('fs').createReadStream(self.staticPath + Request.url).pipe(Response); /* * Tell the main handler we have delt with the response * */ callback(true); }) } module.exports = new StaticFeeder(); })(); 

任何人都可以帮我解决这个问题,我不知道如何告诉pipe道压缩与gzip。

谢谢

其实,我有一个关于这个东西的博客文章。 http://dhruvbird.blogspot.com/2011/03/node-and-proxydecorator-pattern.html

您将需要:

 npm install compress -g 

在使用它之前。

基本思想围绕使用pipe道添加function。

但是,对于你的用例,你最好把node.js放在nginx后面去做所有的gzip,因为node.js是一个单独的进程(实际上不是),gzip例程会占用你的进程的CPU 。

你可以通过一个压缩stream来pipe道:

 var fs = require('fs') var zlib = require('zlib') fs.createReadStream(file) .pipe(zlib.createGzip()) .pipe(Response) 

假定文件已经不被压缩,并且已经设置了响应的所有标题。