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

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

问题描述

如何在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/blob/cfcb1de130867197cbc9c6012b7d84 /lib/fs.js#L1597-L1620

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

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

编辑2015年4月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.

我的建议是将您的可读流置于已暂停模式,至少防止上游数据源中的进一步处理.如 the文档

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天全站免登陆