【问题标题】:Test whether the actual output is a terminal or not in node.js在 node.js 中测试实际输出是否是终端
【发布时间】:2011-10-28 04:05:44
【问题描述】:

我正在为我的一个程序编写命令行界面,如果合适的话,我想使用winston 的彩色输出(输出是一个终端,它没有重定向到文件)。

在 bash 中,它可以通过 -t 测试来完成,正如 SO answer 正确所说的那样。但我正在寻找 node.js 替代品来测试它。

【问题讨论】:

    标签: command-line node.js command-line-interface


    【解决方案1】:

    与您链接到的 bash 示例类似,Node 具有处理此问题的“tty”模块。

    要检查输出是否被重定向,您可以使用 'isatty' 方法。 文档在这里:http://nodejs.org/docs/v0.5.0/api/tty.html#tty.isatty

    例如检查stdout是否被重定向:

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

    更新

    在新版本的 Node(从 0.12.0 开始)中,API 在 stdout 上提供了一个标志,因此您可以这样做:

    if (process.stdout.isTTY) {
      console.log('not redirected');
    }
    else {
      console.log('redirected');
    }
    

    【讨论】:

    • 也许 API 已经进化了,但请注意,根据this,检查节点是否在 TTY 上运行的首选方法是询问 process.stdout.isTTY
    • @epidemian 好电话,我更新了答案。 API 肯定已经发展,因为这是一个相当古老的答案。
    猜你喜欢
    • 2016-01-27
    • 1970-01-01
    • 2015-02-07
    • 2014-05-08
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多