如何关闭一个可读流在 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.");
}
});
但这不会停止阅读过程......
Edit:好消息!从 Node.js 8.0.0 开始readable.destroy
正式可用:https://nodejs.org/api/stream.html#stream_read_destroy_error
ReadStream.destroy
您可以致电ReadStream.destroy随时发挥作用。
var fs = require("fs");
var readStream = fs.createReadStream("lines.txt");
readStream
.on("data", function (chunk) {
console.log(chunk);
readStream.destroy();
})
.on("end", function () {
// This may not been called since we are destroying the stream
// the first time "data" event is received
console.log("All the data in the file has been read");
})
.on("close", function (err) {
console.log("Stream has been destroyed and file has been closed");
});
公共职能ReadStream.destroy
没有记录(Node.js v0.12.2),但你可以看看GitHub 上的源代码 (2012 年 10 月 5 日提交).
The destroy
函数内部标记ReadStream
实例被销毁并调用close
函数来释放文件。
您可以收听关闭事件确切地知道文件何时关闭。这结束事件除非数据完全消耗,否则不会触发。
请注意,destroy
(以及close
) 函数特定于fs.ReadStream。没有通用的部分流.可读“界面”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)