1

私は現在、ブラウザに送り返す前にコンテンツを 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 で圧縮するようにパイプに指示する方法についての手がかりがありません。

ありがとう

4

2 に答える 2

1

実際、私はこのことについてのブログ投稿を持っています。http://dhruvbird.blogspot.com/2011/03/node-and-proxydecorator-pattern.html

次のことを行う必要があります。

npm install compress -g

使う前だけど。

基本的な考え方は、パイプを使用して機能を追加することです。

ただし、ユースケースでは、node.js は単一のプロセスであり (実際にはそうではありません)、gzip ルーチンがプロセスの CPU を占有するため、nginx の背後に node.js を置いてすべての gzip を実行する方がよいでしょう。 .

于 2011-04-26T04:42:18.390 に答える
1

圧縮ストリームを介してパイプするだけです:

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

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

ファイルがまだ圧縮されておらず、応答のすべてのヘッダーが既に設定されていると想定しています。

于 2013-03-21T00:53:30.410 に答える