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


版本历史
版本变更
v24.2.0

已添加 'none' 格式作为非操作格式。

v23.5.0, v22.13.0

styleText 现已稳定。

v22.8.0, v20.18.0

尊重 isTTY 和环境变量,例如 NO_COLOR、NODE_DISABLE_COLORS 和 FORCE_COLOR。

v21.7.0, v20.12.0

新增于: v21.7.0, v20.12.0

  • format <string> | <Array> util.inspect.colors 中定义的文本格式或文本格式数组。

    \format <string> | <Array> A text format or an Array of text formats defined in util.inspect.colors.

  • text <string> 要格式化的文本。

    \text <string> The text to to be formatted.

  • options <Object>

    • validateStream <boolean> 当为 true 时,将检查 stream 是否可以处理颜色。默认值:true

      \validateStream <boolean> When true, stream is checked to see if it can handle colors. Default: true.

    • stream <Stream> 如果可以着色,则将验证流。默认值:process.stdout

      \stream <Stream> A stream that will be validated if it can be colored. Default: 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 还提供 italicunderline 等文本格式,你可以将两者结合起来:

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

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

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

完整的格式列表可以在 modifiers 中找到。

\The full list of formats can be found in modifiers.

AltStyle によって変換されたページ (->オリジナル) /