Node.js如何将gzipstreampipe道写入stream

我似乎无法得到这个工作。 我想写一些数据到gzipstream,然后pipegzipstream到一个文件写入stream。 我想在文件完成写入时调用函数。 我目前有:

var gz = zlib.createGzip() .pipe(fs.createWriteStream(gz_path)); gz.write(data); gz.on('error', function(err){ console.log("wtf error", err); }); gz.on('finish', function(){ console.log("write stream is done"); dosomething(); }); 

结束事件或错误事件永远不会被调用。

尝试

 var zlib = require('zlib'); var stream = require('stream'); var util = require('util'); var fs = require('fs'); var gz = zlib.createGzip(); function StringifyStream(){ stream.Transform.call(this); this._readableState.objectMode = false; this._writableState.objectMode = true; } util.inherits(StringifyStream, stream.Transform); StringifyStream.prototype._transform = function(obj, encoding, cb){ this.push(JSON.stringify(obj)); cb(); }; var data = "some data in here"; var rs = new stream.Readable({ objectMode: true }); rs.push(data); rs.push(null); rs.pipe(new StringifyStream()) .pipe(gz) .pipe(fs.createWriteStream('test.gz')) .on('error', function(err){ console.log("wtf error", err); }) .on('finish', function(){ console.log("write stream is done"); // dosomething(); });