19

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

iamsim.me
  • 560
  • 4
  • 17
  • Why not handle this from node? Pass a command line argument to send it to less. It's a lot less flexible but if you want to be aware of it being piped you're losing that flexibility anyway. – Benjamin Gruenbaum Dec 14 '13 at 17:00

2 Answers2

36

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
}
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    @damphat it'd be really odd if it didn't work on windows :) It actually just [delegates to libuv](https://github.com/joyent/node/blob/master/src/tty_wrap.cc#L125) to `uv_get_handle` which just does under `/src/win/` (the windows handling logic) which in `handle.c` that [in turn](https://github.com/joyent/libuv/blob/master/src/win/tty.c#L228) just calls [GetConsoleMode](http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx) :) – Benjamin Gruenbaum Dec 14 '13 at 17:24
  • It has a strange return value. If it is a TTY, it returns `true`, if it isn't, it returns `undefined`. – CMCDragonkai Aug 01 '22 at 06:33
  • This also works with `process.stdin` and for redirect input/output operators (`node ... < file.txt`). Adding this comment in hopes this answer will be easier to find using keywords like "stdin", "redirect"/"bash less than", etc. – Jozef Mikušinec Oct 23 '22 at 17:37
0

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
timtofan
  • 104
  • 4