如何关闭可读流(结束前)?

新手上路,请多包涵

如何在 Node.js 中关闭 可读流

 var input = fs.createReadStream('lines.txt');

input.on('data', function(data) {
   // after closing the stream, this will not
   // be called again

   if (gotFirstLine) {
      // close this stream and continue the
      // instructions from this if
      console.log("Closed.");
   }
});

这会比:

 input.on('data', function(data) {
   if (isEnded) { return; }

   if (gotFirstLine) {
      isEnded = true;
      console.log("Closed.");
   }
});

但这不会停止阅读过程……

原文由 Ionică Bizău 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

调用 input.close() 。它不在文档中,但

https://github.com/joyent/node/blob/cfcb1de130867197cbc9c6012b7e84e08e53d032/lib/fs.js#L1597-L1620

显然可以完成这项工作:) 它实际上做了类似于您的 isEnded 的事情。

编辑 2015 年 4 月 19 日 根据以下评论,并澄清和更新:

  • 这个建议是一个 hack,没有记录。
  • 尽管查看当前的 lib/fs.js 它仍然可以在 1.5 年后工作。
  • 我同意下面关于调用 destroy() 更可取的评论。
  • 如下正确所述,这适用于 fs ReadStreams ,不适用于通用 Readable

至于通用解决方案:至少从我对文档的理解和快速浏览 _stream_readable.js 来看,似乎没有一个。

我的建议是将您的可读流置于 暂停 模式,至少可以防止在上游数据源中进行进一步处理。不要忘记 unpipe() 并删除所有 data 事件侦听器,以便 pause() 实际上暂停,如 文档中所述

原文由 Nitzan Shaked 发布,翻译遵循 CC BY-SA 3.0 许可协议

编辑: 好消息!从 Node.js 8.0.0 开始 readable.destroy 正式可用: https ://nodejs.org/api/stream.html#stream_readable_destroy_error

ReadStream.销毁

您可以随时调用 ReadStream.destroy 函数。

 var fs = require("fs");

var readStream = fs.createReadStream("lines.txt");
readStream
    .on("data", function (chunk) {
        console.log(chunk);
        readStream.destroy();
    })
    .on("end", function () {
        // This may not been called since we are destroying the stream
        // the first time "data" event is received
        console.log("All the data in the file has been read");
    })
    .on("close", function (err) {
        console.log("Stream has been destroyed and file has been closed");
    });

公共函数 ReadStream.destroy 未记录(Node.js v0.12.2),但您可以查看 GitHub 上的源代码2012 年 10 月 5 日提交)。

destroy 函数在内部将 ReadStream 实例标记为已销毁,并调用 close 函数释放文件。

您可以收听 关闭事件 以准确了解文件何时关闭。除非数据被完全消耗,否则不会触发 结束事件


请注意, destroy (和 close )函数特定于 fs.ReadStream 。没有通用流的一部分。 可读 的“接口”。

原文由 Yves M. 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题