在使用节点流时,我注意到几乎每个教程都会教授以下内容:
// 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()
是优选的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)