This function returns a formatted text considering the format passed for printing in a terminal. It is aware of the terminal's capabilities and acts according to the configuration set via NO_COLOR, NODE_DISABLE_COLORS and FORCE_COLOR environment variables.
import { styleText } from 'node:util';
import { stderr } from 'node:process';
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);
util.inspect.colors also provides text formats such as italic, and underline and you can combine both:
console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
When passing an array of formats, the order of the format applied is left to right so the following style might overwrite the previous one.
console.log(
util.styleText(['red', 'green'], 'text'), // green
);
The special format value none applies no additional styling to the text.
In addition to predefined color names, util.styleText() supports hex color strings using ANSI TrueColor (24-bit) escape sequences. Hex colors can be specified in either 3-digit (#RGB) or 6-digit (#RRGGBB) format:
import { styleText } from 'node:util';
// 6-digit hex color
console.log(styleText('#ff5733', 'Orange text'));
// 3-digit hex color (shorthand)
console.log(styleText('#f00', 'Red text'));
The full list of formats can be found in modifiers.