Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether the actual output is a terminal or not in node.js

Tags:

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.

like image 386
KARASZI István Avatar asked Aug 16 '11 15:08

KARASZI István


People also ask

Is node js a terminal?

Because of this we decided to do a mini blog series of two posts of using the terminal for Node. js. js is an asynchronous event-driven JavaScript runtime and is the most effective when building scalable network applications.

How do I find node js in terminal?

To see if Node is installed, open the Windows Command Prompt, Powershell or a similar command line tool, and type node -v . This should print the version number so you'll see something like this v0. 10.35 . Test NPM.

How do I test a JavaScript code in terminal?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.


1 Answers

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'); } 
like image 119
loganfsmyth Avatar answered Dec 21 '22 01:12

loganfsmyth