如何关闭可读流(结束前)? [英] How to close a readable stream (before end)?

查看:26
本文介绍了如何关闭可读流(结束前)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to close a readable stream in 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.");
   }
});

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

But this would not stop the reading process...

推荐答案

调用 input.close().它不在文档中,而是

Invoke input.close(). It's not in the docs, but

https://github.com/joyent/node/16b71c80c5c8c5c8c8c5c8c5c8c8c5c8c8c08c8c8c8c08/lib/fs.js#L1597-L1620

显然可以完成这项工作:) 它实际上与您的 isEnded 类似.

clearly does the job :) It actually does something similar to your isEnded.

EDIT 2015-Apr-19 基于以下评论,并澄清和更新:

EDIT 2015-Apr-19 Based on comments below, and to clarify and update:

  • 此建议是一种黑客行为,未记录在案.
  • 尽管查看当前的 lib/fs.js,它在 1.5 年后仍然有效.
  • 我同意下面关于最好调用 destroy() 的评论.
  • 如下所述,这适用于 fs ReadStreams,而不适用于通用的 Readable
  • This suggestion is a hack, and is not documented.
  • Though for looking at the current lib/fs.js it still works >1.5yrs later.
  • I agree with the comment below about calling destroy() being preferable.
  • As correctly stated below this works for fs ReadStreams's, not on a generic Readable

至于通用解决方案:至少从我对文档的理解和对 _stream_readable.js 的快速浏览来看,它似乎并不存在.

As for a generic solution: it doesn't appear as if there is one, at least from my understanding of the documentation and from a quick look at _stream_readable.js.

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

My proposal would be put your readable stream in paused mode, at least preventing further processing in your upstream data source. Don't forget to unpipe() and remove all data event listeners so that pause() actually pauses, as mentioned in the docs

这篇关于如何关闭可读流(结束前)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆