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