util.styleText Colorizes Terminal Output
Wrap terminal text with util.styleText; validateStream defaults to true so ANSI is emitted only when stdout can render colors; pass false to always wrap.
Code
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['));Output
Captured from a sandboxed run of this snippet in the build pipeline.
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: trueHow it works
util.styleText Colorizes Terminal Output comes down to the function renderRow.
styleText comes from node:util — Node.js core modules the runtime ships with.
Watch out for
node:utilis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Using it
The primary signature is function renderRow(label, value, ok)
The demo output is labeled (default validateStream on stdout:, validateStream false always wraps:, has ANSI escape prefix:); each label names the call that printed it.
Key statements
return styleText('bold', label) + ' ' + mark + ' ' + value;
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does this require external packages?
- No — `node:util` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.