Node.js流API泄漏

问题描述 投票:9回答:2

[在玩节点流时,我注意到几乎每个教程都讲类似的东西:

// Get Google's home page.
require('http').get("http://www.google.com/", function(response) {
  // The callback provides the response readable stream.
  // Then, we open our output text stream.
  var outStream = require('fs').createWriteStream("out.txt");

  // Pipe the input to the output, which writes the file.
  response.pipe(outStream);
});

但是我认为这是一段非常危险的代码。如果文件流在某个时刻引发异常会怎样?我认为文件流可能会泄漏内存,因为根据文档,文件流显然没有关闭。

我应该注意吗?我认为node.js流应该处理情况...

node.js http asynchronous stream pipe
2个回答
2
投票

排除Node VM中的所有错误,如果在打开流之后有一个异常会中断操作,我希望最终在VM进行垃圾收集期间,VM会检测到没有内容引用该流,并且会对其进行收集,从而处置与之关联的资源。

所以我不称其为“泄漏”。

仍然存在与not处理异常或不关闭流有关的问题。例如,在Unix类型的系统上,当创建与磁盘上文件相对应的流时,将使用文件描述符。一个进程一次可以打开多少个文件描述符是有限制的。因此,如果未显式关闭其流的进程设法将其中许多未关闭而导致在下一次垃圾回收之前达到文件描述符限制,则它将崩溃。


7
投票

为了避免文件描述符泄漏,您还需要:

var outStream = require('fs').createWriteStream("out.txt");

// Add this to ensure that the out.txt's file descriptor is closed in case of error.
response.on('error', function(err) {
  outStream.end();
});

// Pipe the input to the output, which writes the file.
response.pipe(outStream);

另一个未公开的方法是outStream.destroy(),它也关闭了描述符,但是似乎更喜欢outStream.end()

© www.soinside.com 2019 - 2024. All rights reserved.