getColorCode
getColorCode converts any AnyColor value — a named 4-bit color, an 8-bit palette code, or a 24-bit RGB object — into its ANSI SGR escape sequence. It is the low-level building block that s() uses internally, exposed so you can construct raw ANSI strings when you need direct control.
Signature
function getColorCode(color: AnyColor | undefined, isBackground: boolean): string
Parameters
color: AnAnyColorvalue — one of:- A named 4-bit string from the
Colortype (e.g."red","cyan"). Produces codes in the 30–37 / 40–47 range. - An
EightBitColorValueobject created byeightBit(code). ProducesESC[38;5;<code>m/ESC[48;5;<code>m. - An
RGBColorValueobject created byrgb(r, g, b)orhex(str). ProducesESC[38;2;r;g;bm/ESC[48;2;r;g;bm.
undefined.- A named 4-bit string from the
isBackground: Whentrue, returns the background variant of the code; whenfalse, returns the foreground variant.
Return Value
A raw ANSI escape string, for example:
- Named foreground:
"\x1b[32m"(green) - Named background:
"\x1b[42m"(green bg) - 8-bit foreground:
"\x1b[38;5;208m"(orange) - RGB foreground:
"\x1b[38;2;255;136;0m"
Returns an empty string for undefined input.
Usage
import { getColorCode, cls } from "ts-better-console";
const fg = getColorCode("green", false); // "\x1b[32m"
const bg = getColorCode("black", true); // "\x1b[40m"
console.log(fg + bg + "Styled text" + cls);
Want to support this project?
If you find ts-better-console useful and want to support its development, consider starring the GitHub repository or buying me a coffee! Your support helps me dedicate more time to improving the library and adding new features.
Want to contribute to this project?
Contributions are welcome! If you're interested in improving the library, fixing bugs, or adding new features, feel free to check out the GitHub repository and submit a pull request. Whether you're a seasoned developer or new to open source, your contributions can make a difference!