Check if a stream is process.stdout
Asked Answered
T

1

0

Is there an elegant way to determine if a stream is process.stdout

I am working with streams and will like to end the stream, but found out that if the stream is process.stdout an error is thrown because process.stdout is a special stream that cannot be closed. So want to end all streams except it's process.stdout

I tried using a try and catch, but the process.stdout error ends the node process, ignoring the try and catch.

Teneshatenesmus answered 7/1, 2017 at 13:0 Comment(0)
S
0

Perhaps this is naive of me, but I'd think you can just check with !==:

if (theStream !== process.stdout) {
    theStream.end();
}

Streams are objects, and there's only one process.stdout, so...

Sarraute answered 7/1, 2017 at 13:3 Comment(6)
I personally think a try/catch block, which eats the exception, is quite possibly the best way to do it - obviously rethrowing the error if it is not the exact one you expect :)Wray
@Barnabus: I just read the last sentence in the question (which I'd somehow missed), where the OP suggests doing that blows up the process. (Which seems very surprising.)Sarraute
@Barnabus: Wow, and I've just verified that with Node v4 and Node v7.Sarraute
That is suprising. Especially considering the docs mention that calling end() throws! You would have thought the error would be catchableWray
@Barnabus: You can indeed catch that exception. But then the next time you try to write to process.stdout (for instance, via console.log), it throws with Error: write after end.Sarraute
Another method I found was this "process.stdout instanceof require('stream').Writable" will return false, but true for other types of streams. Not sure how far it will work thoughTeneshatenesmus

© 2022 - 2024 — McMap. All rights reserved.