Node.js – 产卵gzip过程

我想用Node.js来gzip一些数据…

具体来说,我有'BUF'的数据,我想写一个gzipforms的这个'stream'。

这是我的代码:

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'); }); }); 

麻烦的是,这根本行不通! 我不确定产卵过程和pipe道数据的确切语法。

任何帮助不胜感激。

提前谢谢了,

编辑:这里是我从中得到的想法的原始工作代码。 该项目位于: 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; }; 

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

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

为什么不简单地使用“灵感来源”而不是复制代码的gzip节点库?

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

应该使用图书馆工作。 要安装它,只需在terminal中inputnpm install gzip