Node.js Stream API泄漏

Kr0*_*r0e 9 asynchronous http pipe stream node.js

在玩节点流时,我注意到几乎每个教程都教导如下:

// 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);
});
Run Code Online (Sandbox Code Playgroud)

但在我看来,这是一个非常危险的部分代码.如果文件流在某个点引发异常会发生什么?我认为文件流可能会泄漏内存,因为根据文档,文件流显然不是很接近.

我应该关心吗?在我的选项node.js流应该处理情况......

DS.*_*DS. 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);
Run Code Online (Sandbox Code Playgroud)

另一个未记录的方法是outStream.destroy()关闭描述符,但似乎outStream.end()是首选.


Lou*_*uis 3

除非 Node 的 VM 中存在任何错误,如果在打开流后出现中断操作的异常,我希望最终在垃圾收集期间,VM 将检测到没有任何内容引用流并收集它,从而处理与其相关的资源。

所以我不会称之为“泄漏”。

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