【问题标题】:gzipping a file with nodejs streams causes memory leaks使用 nodejs 流压缩文件会导致内存泄漏
【发布时间】:2013-11-23 22:27:19
【问题描述】:

我正在尝试做看起来很简单的事情:获取一个文件名为 X 的文件,并创建一个 gzip 压缩版本作为“X.gz”。 Nodejs 的 zlib 模块没有方便的 zlib.gzip(infile, outfile),所以我想我会使用一个输入流、一个输出流和一个 zlib gzipper,然后将它们管道化:

var zlib = require("zlib"),
    zipper = zlib.createGzip(),
    fs = require("fs");

var tryThing = function(logfile) {
  var input = fs.createReadStream(logfile, {autoClose: true}),
       output = fs.createWriteStream(logfile + ".gz");

  input.pipe(zipper).pipe(output);

  output.on("end", function() {
    // delete original file, it is no longer needed
    fs.unlink(logfile);

    // clear listeners
    zipper.removeAllListeners();
    input.removeAllListeners();
  });
}

然而,每次我运行这个函数,Node.js 的内存占用增加了大约 100kb。我是不是忘了告诉溪流他们应该再次杀死自己,因为不再需要它们?

或者,或者,有没有办法只 gzip 文件而不用担心流和管道?我尝试在谷歌上搜索“node.js gzip a file”,但它只是指向 API 文档的链接,以及关于 gzipping 流和缓冲区的堆栈溢出问题,而不是如何 gzip 文件。

【问题讨论】:

    标签: node.js stream zlib


    【解决方案1】:

    我认为您需要正确地 unpipeclose 流。仅仅removeAllListeners() 可能不足以清理这些东西。因为流可能正在等待更多数据(因此不必要地在内存中保持活动状态。)

    你也没有关闭输出流,IMO 我会听输入流的end 而不是输出。

    // cleanup
    input.once('end', function() {
      zipper.removeAllListeners();
      zipper.close();
      zipper = null;
      input.removeAllListeners();
      input.close();
      input = null;
      output.removeAllListeners();
      output.close();
      output = null;
    });
    

    另外,我认为从zlib.createGzip() 返回的流一旦结束就不能共享。您应该在 tryThing 的每次迭代中创建一个新的:

    var input = fs.createReadStream(logfile, {autoClose: true}),
      output = fs.createWriteStream(logfile + ".gz")
      zipper = zlib.createGzip(); 
    
    input.pipe(zipper).pipe(output);
    

    尚未对此进行测试,因为我现在附近没有内存配置文件工具。

    【讨论】:

    • 优点,虽然如果 close() 被调用,removealllisteneres 和空赋值就不再需要了。我最终选择了一个直接的 in.pipe(out) 并重新分配每个周期,然后使用 less pipe-y readfile/gzip/writefile/unlink 压缩最终的输出文件,但你仍然会得到一个有用的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2021-09-02
    • 2010-11-18
    • 1970-01-01
    • 2023-03-06
    • 2012-11-16
    • 2021-03-23
    相关资源
    最近更新 更多