← 中文资源

简体中文版本

util.styleText 为终端输出着色

用 util.styleText 给终端文本加颜色与粗体:validateStream 默认为 true,只有 stdout 能渲染颜色时才输出 ANSI 码;传 validateStream: false 可跳过校验、始终包裹文本。

阅读英文原文

运行结果

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

build PASS 42s
tests PASS 312 passed
lint FAIL 2 warnings
default validateStream on stdout: "info"
validateStream false always wraps: "\u001b[36minfo\u001b[39m"
has ANSI escape prefix: true

实现说明

util.styleText 为终端输出着色的核心是函数 renderRow。 styleText 来自 node:util——Node.js 随运行时自带的核心模块。

使用要点

  • 无需安装:node:util 随 Node.js 本体提供。
  • 跑完文件,输出里会留下标记——default validateStream on stdout:、validateStream false always wraps:、has ANSI escape prefix:。

常见问题

需要安装第三方包吗?

不需要——node:util 是 Node.js 内建模块,无需安装。

入口签名:function renderRow(label, value, ok)

核心语句

return styleText('bold', label) + ' ' + mark + ' ' + value;

代码示例

import { styleText } from 'node:util';

function renderRow(label, value, ok) {
  const mark = ok ? styleText('green', 'PASS') : styleText('red', 'FAIL');
  return styleText('bold', label) + ' ' + mark + ' ' + value;
}

// On a TTY these rows come out colored; when stdout is redirected to a file
// or pipe, the ANSI codes are suppressed and the rows print as plain text.
console.log(renderRow('build', '42s', true));
console.log(renderRow('tests', '312 passed', true));
console.log(renderRow('lint', '2 warnings', false));

// validateStream defaults to true: the format is applied only when the
// target stream (process.stdout here) can render colors, so redirected
// output stays free of escape sequences.
const plain = styleText('cyan', 'info');
console.log('default validateStream on stdout:', JSON.stringify(plain));

// validateStream: false skips the stream check and always wraps the text,
// which is what a file or formatter sink needs to keep its colors.
const forced = styleText('cyan', 'info', { validateStream: false });
console.log('validateStream false always wraps:', JSON.stringify(forced));
console.log('has ANSI escape prefix:', forced.startsWith('\u001b['));