Node.js如何将gzip流导入写入流?

9

我似乎无法让它正常工作。我想将一些数据写入gzip流,然后将gzip流传输到文件写入流中。然后在文件写入完成时调用一个函数。我目前有以下代码:

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

完成事件或错误事件从未被调用。

4
在写完数据后,尝试使用 end() 关闭 gz 流。 - user568109
4个回答

3

我的例子:

async function run(){

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

var gz = zlib.createGzip();
gz.on('error', function(err){    console.log(err.stack);   });
// gz.on('finish', function() {    console.log("finished compression, now need to finish writing...");   });

var f = fs.createWriteStream('test.txt.gz');
f.on('error', function(err){    console.log(err.stack);       });
f.on('finish', function() {    console.log("Write success.");   });

gz.pipe(f);

// if stream.write returns false need to wait for drain,
// for example using await for a promise in an async function, or maybe run the callback on drain
if(!gz.write('test','utf-8'))
  await new Promise( (resolve,reject)=> gz.once('drain', resolve) )

gz.end();

console.log("Compress zip file success.");

}

run();

问题中的代码存在三个问题

  • pipe方法返回它的参数,而不是上一个调用对象
  • 需要结束流,以便将数据写入输出
  • 最好在使用事件前对其进行设置

// needded for code in question to run:
function dosomething(){

}
var gz_path="test.txt.gz"
var data="test"


//corrected code

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

// pipe retuns its argument, the folowing is correct:
// var f = zlib.createGzip().pipe(fs.createWriteStream(gz_path));

var gz = zlib.createGzip();

gz.pipe(fs.createWriteStream(gz_path));

// it helps to setup events before they fire  
gz.on('error', function(err){
    console.log("wtf error", err);
});

gz.on('finish', function(){
    console.log("write stream is done");
    dosomething();
});

gz.write(data);

// need to end stream for data to be written
gz.end()

1

from here

import { createReadStream, createWriteStream } from 'fs'
import { createGzip } from 'zlib'

const filename = yourFile
// opens the file as a readable stream
createReadStream(filename)
   .pipe(createGzip())
   .pipe(createWriteStream(`${filename}.gz`))
   .on('finish', () => console.log('File is compressed'))

1
尝试
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();
});

没有运气。fs.createWriteStream 的错误会冒泡到 gz.on error 吗? - kevzettler
抱歉,我没有意识到您没有正确转换流。请现在尝试代码。 - Kamrul
值得注意的是,gz只能使用一次。在关闭后,就不能再向其中写入数据了。因此,在流创建期间初始化gz通常比在整个文件中只初始化一次更好。 - h-kippo

0

管道的顺序可能是问题所在。我通过让createGzipcreateWriteStream之前来解决了这个问题。例如:

import Readable from "stream";
import zlib from "zlib";
import fs from "fs";

Readable.from([data])
   .pipe(zlib.createGzip())
   .pipe(fs.createWriteStream(`filePath.gzip`))
   .on("error", (error) => {
      // handle error
   })
   .on("finish", () => {
      // handle success
   })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接