1

我目前正在处理一个项目,该项目需要在将内容发送回浏览器之前对其进行 gZip-ed。

我目前使用简单的读取流并将数据传输到请求的响应中,但我不确定在不阻塞请求的情况下使用 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();
})();

谁能帮我解决这个问题,我不知道如何告诉管道用 gZip 压缩。

谢谢

4

2 回答 2

1

您可以通过压缩流对其进行管道传输:

var fs = require('fs')
var zlib = require('zlib')

fs.createReadStream(file)
.pipe(zlib.createGzip())
.pipe(Response)

假定文件尚未压缩,并且您已经设置了响应的所有标头。

于 2013-03-21T00:53:30.410 回答
1

实际上,我有一篇关于这件事的博客文章。http://dhruvbird.blogspot.com/2011/03/node-and-proxydecorator-pattern.html

您将需要:

npm install compress -g

不过在使用之前。

基本思想围绕着使用管道来添加功能。

但是,对于您的用例,您最好将 node.js 放在 nginx 后面来完成所有 gzip,因为 node.js 是单个进程(实际上不是),并且 gzip 例程会占用您进程的 CPU .

于 2011-04-26T04:42:18.390 回答