Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NodeJS ClearTextStream stream is "ended"?

Tags:

stream

node.js

I have a ClearTextStream for a TLS connection and I want to check if "end" was already called. The actual problem is, that I'm trying to write something into the stream and I get an "write after end" error.

Now to avoid that, I just want to check if "end" was already called. I do have an "close" event, but it isn't fired in all cases.

I can't find it in the documentation and I couldn't find anything like that by googling.

I could check the error event (which is throwing "write after end" for me) and handle the situation there - but is there really no way to check this in the beginning?

Thanks!

like image 911
brdigi Avatar asked Oct 02 '22 10:10

brdigi


1 Answers

If you get a write after end error, that means that you are trying to write data to a Writable stream that has been closed (ie. that can't accept anymore input data). When a writable stream closes, the finish event is emitted (see the documentation). On the other hand, the close event is emitted by a Readable stream, when the underlying resource is closed (for instance when the file descriptor you are reading is closed).

As a ClearTextStream is a Duplex stream, it can emit both close and finish events, but they don't mean the same thing. In your particular case, you should listen to the finish event and react appropriately.

Another solution would be to check the this.ended and this.finished booleans (see the source code), but I wouldn't recommend that as they are private variables and only reflect the implementation details, not the public API.

like image 162
Paul Mougel Avatar answered Oct 05 '22 10:10

Paul Mougel