Node.js ANSI Colors - Console.log with Color Codes
Add colors to Node.js console.log output using ANSI escape codes. Covers raw \x1b sequences, chalk library, and built-in util.inspect.colors for styled CLI output.
Language Examples
Detailed Explanation
Colored Console Output in Node.js
Node.js uses \x1b as the escape character for ANSI sequences. This guide covers both native and library-based approaches.
Raw ANSI Sequences
// Basic colors
console.log("\x1b[31mRed text\x1b[0m");
console.log("\x1b[1;32mBold green\x1b[0m");
// 256 colors
console.log("\x1b[38;5;208mOrange\x1b[0m");
// True color
console.log("\x1b[38;2;255;165;0mTrue orange\x1b[0m");
Color Utility Module
const colors = {
reset: "\x1b[0m",
bold: "\x1b[1m",
dim: "\x1b[2m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
white: "\x1b[37m",
bgRed: "\x1b[41m",
bgGreen: "\x1b[42m",
};
const colorize = (text, color) =>
`${colors[color]}${text}${colors.reset}`;
// Usage
console.log(colorize("Error!", "red"));
console.log(colorize("Success!", "green"));
Tagged Template Literal
function ansi(strings, ...values) {
const codes = { r: 31, g: 32, y: 33, b: 34, m: 35, c: 36 };
return strings.reduce((result, str, i) => {
const val = values[i] !== undefined ? values[i] : "";
return result + str + val;
}, "");
}
console.log(`\x1b[31mRed \x1b[32mGreen \x1b[0m`);
Detecting Color Support
const supportsColor = process.stdout.isTTY
&& !process.env.NO_COLOR
&& process.env.TERM !== "dumb";
function maybeColor(text, code) {
if (supportsColor) {
return `\x1b[${code}m${text}\x1b[0m`;
}
return text;
}
Using with Streams
// Write directly to stdout for more control
process.stdout.write("\x1b[33mProcessing... \x1b[0m");
// ... do work ...
process.stdout.write("\x1b[32mdone\x1b[0m\n");
ESM and TypeScript
// color.ts
export const ANSI = {
red: (s: string) => `\x1b[31m${s}\x1b[0m`,
green: (s: string) => `\x1b[32m${s}\x1b[0m`,
bold: (s: string) => `\x1b[1m${s}\x1b[0m`,
rgb: (r: number, g: number, b: number, s: string) =>
`\x1b[38;2;${r};${g};${b}m${s}\x1b[0m`,
} as const;
console.log(ANSI.red("Error"));
console.log(ANSI.rgb(255, 165, 0, "Orange"));
Use Case
Node.js developers use ANSI colors in CLI tools built with commander or yargs, custom build scripts, test reporters, logging utilities, and npm lifecycle scripts. The lightweight approach with raw escape codes avoids adding dependencies, while libraries like chalk provide a richer API for complex applications. Many popular tools like ESLint, Prettier, and Webpack use colored output extensively.