Question

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

Was it helpful?

Solution

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
}

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top