util.styleText(format, text[, options])


  • format <string> | <Array> util.inspect.colors 中定义的文本格式或文本格式数组,或 #RGB#RRGGBB 形式的十六进制颜色。
  • text <string> 要格式化的文本。
  • options <Object>
    • validateStream <boolean> 当为真时,会检查 stream 是否能够处理颜色。默认值: true
    • stream <Stream> 将验证一个流是否可以着色。默认值: process.stdout

此函数会根据传入的 format 返回格式化文本,以便在终端中打印。它会根据终端的功能进行处理,并根据 NO_COLORNODE_DISABLE_COLORSFORCE_COLOR 环境变量的配置采取相应操作。

🌐 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);const { styleText } = require('node:util');
const { stderr } = require('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 还提供文本格式,如 italic(斜体)和 underline(下划线),并且你可以将两者结合使用:

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
); 

特殊格式值 none 不会对文本应用任何额外样式。

🌐 The special format value none applies no additional styling to the text.

除了预定义的颜色名称外,util.styleText() 还支持使用 ANSI TrueColor(24 位)转义序列的十六进制颜色字符串。十六进制颜色可以使用 3 位(#RGB)或 6 位(#RRGGBB)格式指定:

🌐 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'));const { styleText } = require('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.