【问题标题】:How to gZip content that's passed through a piped readStream如何压缩通过管道 readStream 传递的内容
【发布时间】:2011-04-24 14:41:57
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 似乎没有太多关于 gzip 的信息。我知道的模块无法安装,其他的都没有用,我仍然不知道如何实现它。我希望有人回答你的问题。也尽量不要一直调用require,使用闭包。
  • require 行为作为一个注册表,它只是返回预加载的模块,如果我将它分配给一个变量,那将是完全相同的,除了明显创建一个变量之外,所有内容都被引用见

标签: node.js gzip piping


【解决方案1】:

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

您需要:

npm install compress -g

在使用之前。

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      相关资源
      最近更新 更多