如何在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.");
}
});
但这不会停止阅读过程...
调用input.close()
。它不在文档中,但是
https://github.com/joyent/node/blob/cfcb1de130867197cbc9c6012b7e84e08e53d032/lib/fs.js#L1597-L1620
显然可以完成这项工作:)实际上,它的工作与您的类似isEnded
。
EDIT 2015-Apr-19根据以下评论,并进行澄清和更新:
lib/fs.js
来看,它仍然可以在> 1.5年后使用。destroy()
更好的评论。fs
ReadStreams
,不适用于通用Readable
至于通用解决方案:至少从我对文档的理解和快速浏览来看,它似乎并不存在_stream_readable.js
。
我的建议是将您的可读流置于暂停模式,至少防止上游数据源中的进一步处理。如文档所述,不要忘记unpipe()
并删除所有data
事件监听器,以便pause()
实际上暂停
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句