gpt4 book ai didi

node.js - 如何关闭可读流(结束前)?

转载 作者:IT老高 更新时间:2023-10-28 21:49:21 26 4
gpt4 key购买 nike

如何关闭 readable stream在 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.");
}
});

但这不会停止阅读过程...

最佳答案

编辑:好消息!从 Node.js 8.0.0 开始 readable.destroy 正式可用:https://nodejs.org/api/stream.html#stream_readable_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");
});

公共(public)函数 ReadStream.destroy 没有文档记录(Node.js v0.12.2),但您可以查看 source code on GitHub (Oct 5, 2012 commit)。

destroy 函数在内部将 ReadStream 实例标记为已销毁,并调用 close 函数释放文件。

您可以收听close event确切地知道文件何时关闭。 end event除非数据完全消耗,否则不会触发。


请注意,destroy(和 close)函数是特定于 fs.ReadStream 的。 .没有通用 stream.readable 的一部分“界面”。

关于node.js - 如何关闭可读流(结束前)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com