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

标签 node.js stream fs

如何关闭 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/

相关文章:

node.js - 无法访问中间件内的 req.body

node.js - 在node.js中创建自定义沙箱(只能在某个目录中读取,不能在任何地方写入)

node.js - 无法在 Protractor 中使用nodejs删除文件

java - 为什么将输入读取为流与字符串相比内存效率更高?

testing - Rabbit Stream Cipher (v 1.1) 正确性测试向量

javascript - 即使在 Node.js 中的回调函数之后,函数也会异步运行

node.js - firebase admin json文件可以在github上公开吗?

node.js - 如何模拟 Node.js child_process spawn 函数?

Node.js - 如何使用回调调用异步函数?

当正在读取的文件中的变量等于用户输入时,C++ 为实例创建计数器的方法