How to close a readable stream in 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."); } });
This would be better than:
input.on('data', function(data) { if (isEnded) { return; } if (gotFirstLine) { isEnded = true; console.log("Closed."); } });
But this would not stop the reading process...
cancel() The cancel() method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read.
The 'end' Event in a Readable Stream is emitted when there is no available data to be consumed from the readable stream. And the 'end' event won't be emitted if the data is not fully consumed. It can be done by switching the stream into the flowing mode, or by calling stream.
Readable: streams from which data can be read. For example: fs. createReadStream() lets us read the contents of a file. Duplex: streams that are both Readable and Writable.
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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With