在node.js中测试实际输出是否是终端 [英] Test whether the actual output is a terminal or not in node.js

查看:150
本文介绍了在node.js中测试实际输出是否是终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的一个程序编写命令行界面,我想使用 winston 的彩色输出

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).

在bash中,可以使用 -t

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.

推荐答案

有'tty'模块来处理这个。

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

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

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

例如要检查stdout是否已重定向:

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');
}



更新



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

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');
}

这篇关于在node.js中测试实际输出是否是终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆