2

我正在尝试使用 Node.js 压缩一些数据...

具体来说,我在“buf”中有数据,我想将其压缩形式写入“流”。

这是我的代码:

c1.on('data',function(buf){
                var gzip = spawn('gzip', ['-' + (compressionRate-0),'-c', '-']);

                gzip.stdin.write(buf);
                gzip.stdout.on('data',function(data){
                        console.log(data);
                        stream.write(data,'binary');
                });
});

问题是,它根本行不通!我不确定生成进程并将数据传送给它们的确切语法。

非常感谢任何帮助。

提前谢谢了,

编辑:这是我得到这个想法的原始工作代码。该项目位于:https ://github.com/indutny/node.gzip

任何人都可以弄清楚如何在 node.js 中生成这个,因为我完全被卡住了!


var spawn = require('child_process').spawn,
    Buffer = require('buffer').Buffer;

module.exports = function (data) {
    var rate = 8,
        enc = 'utf8',
        isBuffer = Buffer.isBuffer(data),
        args = Array.prototype.slice.call(arguments, 1),
        callback;

    if (!isBuffer && typeof args[0] === 'string') {
        enc = args.shift();
    }
    if (typeof args[0] === 'number') {
        rate = args.shift() - 0;
    }
    callback = args[0];

    var gzip = spawn('gzip', ['-' + (rate - 0), '-c', '-']);

    var promise = new
    process.EventEmitter,
        output = [],
        output_len = 0;

    // No need to use buffer if no
    callback was provided
    if (callback) {
        gzip.stdout.on('data', function (data) {
            output.push(data);
            output_len += data.length;
        });

        gzip.on('exit', function (code) {
            var buf = new Buffer(output_len);

            for (var a = 0, p = 0; p < output_len; p += output[a++].length) {
                output[a].copy(buf, p, 0);
            }
            callback(code, buf);
        });
    }
    // Promise events  
    gzip.stdout.on('data', function (data) {
        promise.emit('data', data);
    });
    gzip.on('exit', function (code) {
        promise.emit('end');
    });

    if (isBuffer) {
        gzip.stdin.encoding = 'binary';
        gzip.stdin.end(data.length ? data : '');
    } else {
        gzip.stdin.end(data ? data.toString() : '', enc);
    }

    // Return EventEmitter, so node.gzip can be used for streaming 
    // (thx @indexzero for that tip) 
    return promise;
};
4

2 回答 2

2

您为什么不简单地使用“受其启发”的 gzip 节点库而不是复制代码?

var gzip = require('gzip');
c1.on('data' function(buf){
    gzip(buf, function(err, data){
        stream.write(data, 'binary');
    }
}

应该使用图书馆工作。要安装它,只需输入npm install gzip您的终端。

于 2011-06-30T13:51:24.127 回答
1

你需要在 gzip.stdin 上调用 'end' 方法吗?IE:

gzip.stdin.write(buf);
gzip.stdout.on('data',function(data){
        console.log(data);
        stream.write(data,'binary');
});
gzip.stdin.end();           
于 2011-06-30T13:33:30.937 回答