【发布时间】:2013-10-17 02:39:47
【问题描述】:
如何在 Node.js 中关闭 readable stream?
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.");
}
});
但这不会停止阅读过程...
【问题讨论】:
-
警告:这个问题只在
fs模块的上下文中。close在Stream.Readable中不存在。 -
好消息。节点版本 8 提供
stream.destroy() -
你不能打电话给
readable.push(null) && readable.destroy();