How to close a readable stream (before end)?

Edit: Good news! Starting with Node.js 8.0.0 readable.destroy is officially available: https://nodejs.org/api/stream.html#stream_readable_destroy_error

ReadStream.destroy

You can call the ReadStream.destroy function at any time.

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");
    });

The public function ReadStream.destroy is not documented (Node.js v0.12.2) but you can have a look at the source code on GitHub (Oct 5, 2012 commit).

The destroy function internally mark the ReadStream instance as destroyed and calls the close function to release the file.

You can listen to the close event to know exactly when the file is closed. The end event will not fire unless the data is completely consumed.


Note that the destroy (and the close) functions are specific to fs.ReadStream. There are not part of the generic stream.readable “interface”.

Leave a Comment