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.

JavascriptCli Tooling

Code

javascriptsnippet
24 lines
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: true

How 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:util is 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

FAQ

Does this require external packages?
No — `node:util` is a Node.js built-in module; nothing to install.