Reputation: 580
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
Upvotes: 19
Views: 5869
Reputation: 104
you can check whether stdout of running process is piped by looking where its file descriptor points, for example like below
readlink /proc/<your process id>/fd/1
or, more specifically
[[ $(readlink /proc/$(pgrep -f 'node myscript.js')/fd/1) =~ ^pipe ]] && echo piped
Upvotes: 0
Reputation: 276296
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
}
Upvotes: 36