26

I'm writing a command line interface for one of my programs, and I would like to use the colorized output of winston if it's appropriate (the output is a terminal and it's not redirected to a file).

In bash it can be done with the -t test as this SO answer correctly says. But I'm looking for the node.js alternative for testing this.

Community
  • 1
  • 1
KARASZI István
  • 30,900
  • 8
  • 101
  • 128

1 Answers1

39

Similarly to the bash examples you link to, Node has the 'tty' module to deal with this.

To check if output is redirected, you can use the 'isatty' method. Docs here: http://nodejs.org/docs/v0.5.0/api/tty.html#tty.isatty

For example to check if stdout is redirected:

var tty = require('tty');
if (tty.isatty(process.stdout.fd)) {
  console.log('not redirected');
}
else {
  console.log('redirected');
}

Update

In new versions of Node (starting from 0.12.0), the API provides a flag on stdout so you can just do this:

if (process.stdout.isTTY) {
  console.log('not redirected');
}
else {
  console.log('redirected');
}
adius
  • 13,685
  • 7
  • 45
  • 46
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 9
    Maybe the API has evolved, but note that according to [this](http://nodejs.org/api/tty.html#tty_tty), the preferred way to check if a node is running on a TTY is to ask for `process.stdout.isTTY` – epidemian Mar 02 '13 at 01:46
  • 2
    @epidemian Good call, I updated the answer. The API has definitely evolved since this is a pretty old answer. – loganfsmyth Mar 02 '13 at 02:35