I have a stream that may or may not have already ended. If it has ended, I don't want to sit there forever waiting for the end
event. How do I check?
Think of a file being read. There is an end of stream there, the end of the file. If you try to read beyond that, you simply can't. If you have a network connection though, there doesn't need to be an end of stream if you simply wait for more data to be sent.
There's no API for determining whether a stream has been closed. Applications should be (and generally are) designed so it isn't necessary to track the state of a stream explicitly. Streams should be opened and reliably closed in an ARM block, and inside the block, it should be safe to assume that the stream is open.
The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.
Streams have a BaseStream. close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files. lines(Path, Charset)) will require closing.
As of node 12.9.0, readable streams have a readableEnded
property you can check – see readable.readableEnded
in the Stream documentation.
(Writable streams have a corresponding property)
If you absolutely have to, you can check stream._readableState.ended
, at least in node 0.10 and 0.12. This isn't public API though so be careful. Also apparently all streams aren't guarantee to have this property too:
Worth reading on this:
https://github.com/hapijs/hapi/issues/2368
https://github.com/nodejs/node/issues/445
You probably shouldn't check, and instead attach an end
event listener. When the stream ends you will get an end
event.
If a [readable]stream is implemented correctly, you will get an end event when there is nothing left to read. For open-ended streams that don't end, you could implement an activity timer to see how long it's been since the stream was last readable, and decide after a certain amount of time to remove your listeners.
(function() {
var timeout = null;
var WAIT_TIME = 10 * 1000; // 10 Sec
function stopListening( ) {
stream.off('data', listener);
}
function listener( data ) {
clearTimeout(timeout);
timeout = setTimeout(stopListening, WAIT_TIME);
// DO STUFF
}
timeout = setTimeout(stopListening, WAIT_TIME);
stream.on('data', listener);
})();
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