To close a readable stream before end with Node.js, we call the destroy
method.
For instance, we write
const fs = require("fs");
const readStream = fs.createReadStream("lines.txt");
readStream
.on("data", (chunk) => {
console.log(chunk);
readStream.destroy();
})
.on("end", () => {
console.log("All the data in the file has been read");
})
.on("close", (err) => {
console.log("Stream has been destroyed and file has been closed");
});
to create the readStream
with createReadStream
.
Then we call destroy
in the data event handler to close the read stream.