util.styleText(format, text[, options])
稳定性: 1.1 - 处于活跃开发中
format<string> | <Array> 文本格式,或在util.inspect.colors中定义的文本格式数组。text<string> 要格式化的文本。options<Object>
此函数会根据传入的 format 返回格式化文本,以便在终端中打印。它会根据终端的功能进行处理,并根据 NO_COLOR、NODE_DISABLE_COLORS 和 FORCE_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(successMessage);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
); 完整的格式列表可以在 修饰符 中找到。
🌐 The full list of formats can be found in modifiers.