Examples
Real-world code examples
This page walks you through practical, real-world examples of using Chalk to style terminal output in your Node.js applications. You'll see how to combine colors, backgrounds, and text decorations — from simple one-liners to reusable themes and dynamic template literals. Working through these examples gives you a solid foundation for integrating Chalk into CLI tools, logging utilities, and any terminal-facing code.
Before working through these examples, make sure you have:
- Node.js installed (any version that supports ES modules)
- Chalk 5.x installed in your project (
npm install chalk) - A basic understanding of ES module
importsyntax — Chalk 5 is ESM-only - If you are using TypeScript or a CommonJS build tool, use Chalk 4.x instead (see the Chalk v5 release notes)
- Initialize your project if you haven't already:
npm init -y
- Install Chalk:
npm install chalk
- If your project uses CommonJS by default, add
"type": "module"to yourpackage.jsonto enable ES module support required by Chalk 5:
{
"type": "module"
}
- Import Chalk at the top of your file:
import chalk from 'chalk';
Chalk automatically detects your terminal's color support, but you can override this behavior when needed.
chalk.level
Controls the color depth used when rendering styles. You can read or set this property directly on the default chalk instance, but be aware it applies globally to all Chalk consumers in the process.
| Level | Description |
|---|---|
0 | All colors disabled — plain text output |
1 | Basic 16-color support |
2 | 256-color support |
3 | Truecolor support (16 million colors) |
If you need isolated color configuration — for example inside a reusable module — create a dedicated instance instead of modifying the global level:
import { Chalk } from 'chalk';
// This instance always renders with no color, regardless of terminal support
const plainChalk = new Chalk({ level: 0 });
// This instance forces Truecolor output
const richChalk = new Chalk({ level: 3 });
Environment variable overrides
You can also control color support from outside your code:
FORCE_COLOR=1— force basic color (level 1)FORCE_COLOR=2— force 256-color (level 2)FORCE_COLOR=3— force Truecolor (level 3)FORCE_COLOR=0— force disable all color--no-colorflag — disables color--color=256flag — enables 256-color mode--color=16mflag — enables Truecolor mode
These environment overrides take precedence over all other color support checks, making them useful for CI environments or testing.
Once Chalk is imported, you style strings by chaining style names and then calling the last one as a function with your string argument. The API is fully composable — order generally doesn't matter, and later styles take precedence if there's a conflict.
Applying a single style
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
Chaining multiple styles
Chain as many modifiers, colors, and background colors as you need:
console.log(chalk.blue.bgRed.bold('Hello world!'));
Passing multiple arguments
Calling a chalk style with multiple arguments joins them with a space:
console.log(chalk.blue('Hello', 'World!', 'Foo', 'bar'));
// => Hello World! Foo bar
Mixing styled and unstyled text
Concatenate chalk expressions with plain strings:
console.log(chalk.blue('Hello') + ' World' + chalk.red('!'));
Using template literals
Embed chalk expressions directly in template literals for readable multi-value output:
console.log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
Defining reusable themes
Assign chalk chains to variables so you can apply a consistent style throughout your application:
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500');
const info = chalk.cyan;
console.log(error('Error!'));
console.log(warning('Warning!'));
console.log(info('Info'));
Using console.log string substitution
Chalk works seamlessly with Node's built-in string substitution:
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
// => Hello Sindre
Basic color output
Apply a single foreground color to a string:
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
Output: Hello world! rendered in blue.
Chaining color, background, and modifier
Combine a foreground color, background color, and bold modifier in a single expression:
import chalk from 'chalk';
console.log(chalk.blue.bgRed.bold('Hello world!'));
Output: Hello world! in bold blue text on a red background.
Mixing styled and plain text
Concatenate chalk output with unstyled strings:
import chalk from 'chalk';
console.log(chalk.blue('Hello') + ' World' + chalk.red('!'));
Output: Hello in blue, World unstyled, ! in red.
Nesting styles
Nest chalk calls to apply a different style to a substring, then return to the outer style:
import chalk from 'chalk';
console.log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
Output: Hello in red, followed by world underlined on a blue background, then ! in red.
Nesting the same style type
You can nest the same category of style (e.g., two different colors) — the innermost style applies to its segment, and the outer style resumes afterward:
import chalk from 'chalk';
console.log(
chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
)
);
Output: Green text surrounding a bold, underlined blue substring.
Template literal with multiple values
Embed styled values inside a template literal for a readable system status display:
import chalk from 'chalk';
console.log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
Output:
CPU: 90% ← red
RAM: 40% ← green
DISK: 70% ← yellow
Reusable theme variables
Define named styles once and reuse them across your application for consistent log formatting:
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange
console.log(error('Error!'));
console.log(warning('Warning!'));
Output: Error! in bold red; Warning! in orange.
RGB and hex colors (Truecolor)
Use precise colors in terminals that support Truecolor (level 3):
import chalk from 'chalk';
console.log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
console.log(chalk.hex('#DEADED').bold('Bold gray!'));
Output: Custom RGB and hex colors rendered with underline and bold respectively. In terminals without Truecolor support, Chalk automatically downsamples to the nearest supported color.
Hex background color
Background versions of advanced color models are prefixed with bg:
import chalk from 'chalk';
console.log(chalk.bgHex('#DEADED').underline('Custom background color'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Inverted custom background'));
Output: Text rendered on a custom hex or RGB background.
Disabling color with a custom instance
Create an isolated Chalk instance with color disabled — useful for plain-text log files or tests:
import { Chalk } from 'chalk';
const plainChalk = new Chalk({ level: 0 });
console.log(plainChalk.red('This will not be red'));
Output: This will not be red — no ANSI codes emitted.
Validating style names programmatically
If you wrap Chalk and accept user-supplied style names, use the exported name arrays to validate input before applying it:
import { modifierNames, foregroundColorNames } from 'chalk';
console.log(modifierNames.includes('bold')); // => true
console.log(foregroundColorNames.includes('pink')); // => false
No colors appear in the terminal
Symptom: Chalk output looks like plain text with no ANSI color codes applied.
Likely causes:
- Your terminal does not support ANSI colors.
chalk.levelhas been set to0somewhere in your code or a dependency.- The
--no-colorflag orFORCE_COLOR=0environment variable is active.
Fix: Check chalk.level at runtime (console.log(chalk.level)). If it is 0, override it or force color via the environment: FORCE_COLOR=1 node your-script.js. On Windows, switch to Windows Terminal for full color support.
SyntaxError: Cannot use import statement in a module or require() of ES Module
Symptom: Your application throws an import or require error when loading Chalk.
Likely cause: Chalk 5 is ESM-only. If your project uses CommonJS (require), or a TypeScript/bundler setup that compiles to CommonJS, it is incompatible with Chalk 5.
Fix: Either add "type": "module" to package.json and use import syntax, or downgrade to Chalk 4 which ships a CommonJS build:
npm install chalk@4
Colors display differently across machines
Symptom: Hex or RGB colors look different (or fall back to basic colors) on some terminals.
Likely cause: Chalk automatically detects color support and downsamples colors to the highest level the terminal reports. A terminal with level 1 support will map a full RGB value to the nearest basic ANSI color.
Fix: This is expected behavior. If you need consistent rich color output (e.g., in CI), force Truecolor mode: FORCE_COLOR=3 node your-script.js. Do not force a high color level in library code — only do this in application-level entry points.
Styles are not applied inside a reusable module
Symptom: Color works in your top-level script but not inside an imported module.
Likely cause: Another part of the codebase has set chalk.level = 0 on the shared global instance, disabling output for all consumers.
Fix: In your reusable module, create a dedicated Chalk instance so your settings are isolated:
import { Chalk } from 'chalk';
const chalk = new Chalk();
This prevents external code from affecting your module's color output.
chalk.hex or chalk.rgb throws or produces unexpected output
Symptom: Calling chalk.hex('#FF0000') or chalk.rgb(255, 0, 0) without passing a string argument returns a Chalk builder object rather than a styled string, or throws.
Likely cause: You called the color method but forgot to call the returned function with a string.
Fix: Advanced color methods return a builder — you must call it with your target string:
// ❌ Wrong — missing the string call
const styled = chalk.hex('#FF0000');
// ✅ Correct
const styled = chalk.hex('#FF0000')('My red text');