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


  • format <string> | <Array> 文本格式,或在 util.inspect.colors 中定义的文本格式数组。
  • text <string> 要格式化的文本。
  • options <Object>
    • validateStream <boolean> 如果为 true,将检查 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.】

完整的格式列表可以在 修饰符 中找到。

【The full list of formats can be found in modifiers.】