node.jsで出力がTTYかどうか判断する

perlでいうと

if (-t STDOUT) {
    say 'tty';
}
else {
    say 'not tty';
}

こういうことがやりたくてnodeだとこうするといけるみたい。

var tty = require('tty');

if (tty.isatty(1)) {
    console.log('tty');
}
else {
    console.log('not tty');
}

1はSTDOUTね。これで

$ node test.js
tty
$ node test.js > foo.txt
$ cat foo.txt
not tty

ってなる。

標準出力に色つけて出力すると、ログとかに書き出したときエスケープシーケンスが入るのでそういうときに使えるかな。