Node.jsstreamAPI泄漏

在玩节点stream的时候,我注意到几乎所有的教程都教了一些东西:

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

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

我应该在乎吗? 在我的选项node.jsstream应该处理情况…

如果在打开stream之后,如果有一个中断操作的exception,我希望最终在垃圾回收过程中,VM会检测到没有任何东西指向stream并收集它,从而处理与之相关的资源。

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

处理exception仍然存在问题,或者不closuresstream。 例如,在Unixtypes的系统上,当创build一个对应于磁盘上的文件的stream时,使用文件描述符。 一个进程一次可以打开多less个文件描述符是有限制的。 因此,如果一个没有明确closures它的stream的进程设法让它们中的很多未被closures,以至于在下一次垃圾回收之前碰到文件描述符限制,它将会崩溃。

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

 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.destroy() ,它也closures了描述符,但似乎outStream.end()是首选。