在玩 Node 流时,我注意到几乎每个教程都讲授如下内容:
// 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 流应该处理各种情况......
最佳答案
为避免文件描述符泄漏,您还需要:
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()
。
关于Node.js Stream API 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449055/