Search code examples
node.jsshellpipetty

How to detect if Node's process.stdout is being piped?


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


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
    }