Categories
JavaScript Answers

How to close a readable stream before end with Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *