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

前端 未结 1 800
借酒劲吻你
借酒劲吻你 2021-01-01 12:51

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\'

相关标签:
1条回答
  • 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');
    }
    
    0 讨论(0)
提交回复
热议问题