如何在 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 许可协议
调用
input.close()
。它不在文档中,但https://github.com/joyent/node/blob/cfcb1de130867197cbc9c6012b7e84e08e53d032/lib/fs.js#L1597-L1620
显然可以完成这项工作:) 它实际上做了类似于您的
isEnded
的事情。编辑 2015 年 4 月 19 日 根据以下评论,并澄清和更新:
lib/fs.js
它仍然可以在 1.5 年后工作。destroy()
更可取的评论。fs
ReadStreams
,不适用于通用Readable
至于通用解决方案:至少从我对文档的理解和快速浏览
_stream_readable.js
来看,似乎没有一个。我的建议是将您的可读流置于 暂停 模式,至少可以防止在上游数据源中进行进一步处理。不要忘记
unpipe()
并删除所有data
事件侦听器,以便pause()
实际上暂停,如 文档中所述