Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 714
simme Avatar asked Dec 14 '13 16:12

simme


People also ask

Is process stdout a stream in node 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.

What does process stdout do?

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.

What is process Stdin in node JS?

The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event.


1 Answers

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
}
like image 140
Benjamin Gruenbaum Avatar answered Oct 25 '22 23:10

Benjamin Gruenbaum