Is there any way I can detect if the output from my Node.js script is being piped to something other then the terminal?
I would like some way of detecting if this is happening:
node myscript.js | less
Or if this is happening:
node myscript.js
If you've been using Node. js for a while, you've definitely run into streams. HTTP connections are streams, open files are streams; stdin, stdout, and stderr are all streams as well.
It prints the information that was obtained at the point of retrieval and adds a new line. Using process. stdout for a variable that shows an object.
The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event.
The easiest way would be process.stdout.isTTY
(0.8 +):
$ node -p -e "Boolean(process.stdout.isTTY)"
true
$ node -p -e "Boolean(process.stdout.isTTY)" | cat
false
(example from the official documentation)
Alternatively you can use the tty
module for finer grained control:
if (require('tty').isatty(1)) {
// terminal
}
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