实现说明
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');