← 中文资源

简体中文版本

isTTY 判断是否终端输出

先看 process.stdout.isTTY 再决定要不要 ANSI 颜色:管道与重定向时保持纯文本,FORCE_COLOR 可强制开启,这是每个 CLI 的标配判断。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

report      : deploy finished
stdout isTTY: undefined
interactive : false
color forced: false
stdin isTTY : no

实现说明

isTTY 判断是否终端输出以函数 headline为骨架。 配置来自环境变量——读取 FORCE_COLOR、TERM,同一份代码在不同环境切换行为而无需改动。

使用要点

  • 守卫 useColor 满足时靠提前的 return 短路流程。
  • 演示输出是带标签的(stdout isTTY:、interactive :、color forced:),每个操作都会留下自己的一行标注。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 headline。

签名一览:function headline(text)

核心语句

return '\x1b[1;36m' + text + '\x1b[0m';
}
return text;
}

代码示例

// CLI output should style itself only when a human is watching it.
const isInteractive = process.stdout.isTTY === true;
const colorForced = process.env.FORCE_COLOR === '1';
const useColor = colorForced || (isInteractive && process.env.TERM !== 'dumb');

function headline(text) {
  if (useColor) {
    return '\x1b[1;36m' + text + '\x1b[0m';
  }
  return text;
}

console.log('report      :', headline('deploy finished'));
console.log('stdout isTTY:', process.stdout.isTTY);
console.log('interactive :', isInteractive);
console.log('color forced:', colorForced);

// stdin drives prompt-vs-flags decisions the same way
console.log('stdin isTTY :', process.stdin.isTTY ?? 'no');