跳到主要内容

colorize [给文本着色]

TS JS Deno

在控制台中添加特殊字符到文本中以彩色打印(与 console.log() 结合使用)。

使用模板文字和特殊字符为字符串输出添加适当的颜色代码。 对于背景颜色,添加一个在字符串末尾重置背景颜色的特殊字符。

typescript
export const colorize = new (class {
color = (code: number, ended = false, ...messages: any[]) =>
`\x1b[${code}m${messages.join(" ")}${ended ? "\x1b[0m" : ""}`;
black = this.color.bind(null, 30, false);
red = this.color.bind(null, 31, false);
green = this.color.bind(null, 32, false);
yellow = this.color.bind(this, 33, false);
blue = this.color.bind(this, 34, false);
magenta = this.color.bind(this, 35, false);
cyan = this.color.bind(this, 36, false);
white = this.color.bind(this, 37, false);
bgBlack = this.color.bind(this, 40, true);
bgRed = this.color.bind(this, 41, true);
bgGreen = this.color.bind(this, 42, true);
bgYellow = this.color.bind(this, 43, true);
bgBlue = this.color.bind(this, 44, true);
bgMagenta = this.color.bind(this, 45, true);
bgCyan = this.color.bind(this, 46, true);
bgWhite = this.color.bind(this, 47, true);
})();

const color = colorize;
typescript
console.log(color.red("foo")); // 'foo' (red letters)
console.log(color.bgBlue("foo", "bar")); // 'foo bar' (blue background)
console.log(color.bgWhite(color.yellow("foo"), color.green("foo"))); // 'foo bar' (first
//word in yellow letters, second word in green letters, white background for both)

console.log(colorize.red("foo")); // 'foo' (red letters)
console.log(colorize.bgBlue("foo", "bar")); // 'foo bar' (blue background)
console.log(colorize.bgWhite(colorize.yellow("foo"), colorize.green("foo"))); // 'foo bar' (first
//word in yellow letters, second word in green letters, white background for both)