Chalk is a popular Node.js library for terminal string styling. It enables terminal applications to format output with colors, bold text, background highlights, and custom Hex/RGB color schemes.
Install Chalk in your Node.js project:
npm install chalkIf using TypeScript and tsx as your runner:
npm install -D typescript tsx @types/nodeChalk provides direct color methods for standard terminal colors:
import chalk from "chalk";
console.log(chalk.green("Operation successful"));
console.log(chalk.red("Error occurred"));
console.log(chalk.yellow("Warning issue"));
console.log(chalk.blue("Informational message"));
console.log(chalk.gray("Debug logs"));Combine color methods with text modifiers like bold, dim, italic, underline, and strikethrough:
console.log(chalk.bold.green("Bold Green Success"));
console.log(chalk.underline.blue("Underlined Blue Link"));
console.log(chalk.bold.red.underline("Critical System Failure"));Apply background colors using the bg prefix:
console.log(chalk.bgRed.white(" ERROR "));
console.log(chalk.bgGreen.black(" SUCCESS "));
console.log(chalk.bgYellow.black(" WARNING "));Specify exact color codes matching your application branding:
// Custom Hex Colors
console.log(chalk.hex("#FFA500")("Orange text output"));
console.log(chalk.hex("#00FF88").bold("Neon green header"));
// RGB Colors
console.log(chalk.rgb(255, 136, 0)("Custom RGB orange"));Style specific variables inside longer strings without affecting surrounding text:
const movie = "Interstellar";
// Only the variable is styled
console.log(`Now playing: ${chalk.cyan.bold(movie)} in theaters.`);
// Nested styling inside a colored block
console.log(
chalk.green(`Successfully added ${chalk.bold(movie)} to your watchlist.`)
);Define reusable style functions to maintain consistent coloring across your codebase:
import chalk from "chalk";
// Define project color theme
export const theme = {
success: chalk.bold.green,
error: chalk.bold.red,
warning: chalk.bold.yellow,
info: chalk.cyan,
subtle: chalk.gray
};
// Usage across services
console.log(theme.success("Data saved successfully"));
console.log(theme.error("File not found"));