Node.js Stream API 泄​​漏

标签 node.js http asynchronous stream pipe

在玩 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/

相关文章:

javascript - 如何避免 jimp 阻塞 Node.js 代码

node.js - 使用 Mocha 读取生态系统变量(单元测试)

node.js - 如何获取在nodejs中运行脚本的文件的当前路径

java - Tomcat 在一定数量的请求后拒绝连接

http - 使用 Selenium : How to modify or inject into HTTP Post Data Request Header?

java - Musicbrainz 查询区分大小写吗?

c# - 如何访问放置在该 void 之外的 async void 中的字符串的值

javascript - 使用默认值和删除额外键的 NodeJS 对象转换

c - ReadFileEx/WriteFileEx是否不需要lpCompletionRoutine和使用GetOverlappedResult?

asynchronous - node.js 的 console.log 是异步的吗?