Usage Patterns
Common integration patterns and best practices
This page covers the most common patterns for integrating Chalk into your Node.js applications, from basic string styling to advanced theme creation and color configuration. Chalk's chainable API lets you compose multiple styles in a single expression, keeping your logging and CLI output code concise and readable. Whether you're building a CLI tool, a development server, or any application that writes to the terminal, these patterns will help you use Chalk effectively and idiomatically.
Before you begin, make sure you have the following:
- Node.js installed (any version that supports ES modules)
- npm (bundled with Node.js) to install the package
- Chalk 5.x — note that Chalk 5 is ESM-only. If your project uses CommonJS (
require()) or TypeScript with a build tool, use Chalk 4.x instead. See the Chalk v5 release notes for details. - A terminal emulator that supports ANSI escape codes (most modern terminals on macOS, Linux, and Windows Terminal on Windows qualify)
-
Install Chalk from npm:
npm install chalk -
Import Chalk in your JavaScript file using ES module syntax:
import chalk from 'chalk';Chalk 5 is ESM only. Your project must use ES modules (
"type": "module"inpackage.json, or.mjsfile extensions). If you need CommonJS (require) compatibility, install Chalk 4 instead:npm install chalk@4Then import it with:
const chalk = require('chalk'); -
Verify the installation by running a quick test:
import chalk from 'chalk'; console.log(chalk.green('Chalk is working!'));If you see green text in your terminal, Chalk is installed and working correctly.
Chalk automatically detects the color support level of the terminal it runs in, so no configuration is required for most use cases. When you do need to control color behavior explicitly, the following options are available.
chalk.level
The level property controls how much color Chalk applies to output. You can read or set it at runtime:
import chalk from 'chalk';
console.log(chalk.level); // e.g., 3 on a Truecolor terminal
| Level | Description |
|---|---|
0 | All colors disabled — plain text only |
1 | Basic 16-color support |
2 | 256-color support |
3 | Truecolor support (16 million colors) |
Setting chalk.level affects all Chalk consumers globally in the same process. Only do this in application-level code, not in reusable libraries or modules.
Creating a scoped instance
If you need to configure color level in a reusable module without affecting the global Chalk instance, create a new instance using the Chalk constructor:
import { Chalk } from 'chalk';
const customChalk = new Chalk({ level: 1 });
console.log(customChalk.blue('Basic blue, regardless of terminal support'));
This is useful for testing output in constrained environments or when writing libraries that ship their own styled output.
Environment variable and flag overrides
Chalk's color detection can be overridden from outside your code:
| Override | Effect |
|---|---|
FORCE_COLOR=1 | Force level 1 (basic colors) |
FORCE_COLOR=2 | Force level 2 (256 colors) |
FORCE_COLOR=3 | Force level 3 (Truecolor) |
FORCE_COLOR=0 | Disable all colors |
--color CLI flag | Enable colors |
--no-color CLI flag | Disable colors |
--color=256 | Enable explicit 256-color mode |
--color=16m | Enable explicit Truecolor mode |
FORCE_COLOR takes precedence over all other color support checks.
Stderr support
If you write styled output to stderr, use chalkStderr instead of the default chalk instance. It is configured with color support detected for the stderr stream:
import { chalkStderr } from 'chalk';
console.error(chalkStderr.red('Something went wrong'));
Applying a single style
Call any style as a method, passing the string you want to style as an argument:
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
Chaining multiple styles
Chalk's API is chainable — append as many styles as you need before calling the final method with your string. Later styles take precedence in case of a conflict, so chalk.red.yellow.green is equivalent to chalk.green.
import chalk from 'chalk';
console.log(chalk.blue.bgRed.bold('Hello world!'));
Mixing styled and unstyled strings
Concatenate styled and plain strings as you would any JavaScript string:
import chalk from 'chalk';
console.log(chalk.blue('Hello') + ' World' + chalk.red('!'));
Passing multiple arguments
You can pass multiple strings to a Chalk method. They are joined with a space:
import chalk from 'chalk';
console.log(chalk.blue('Hello', 'World!', 'Foo', 'bar'));
// => 'Hello World! Foo bar' (all in blue)
Nesting styles
Nest Chalk calls to apply different styles to substrings within a larger styled string. The outer style resumes after the inner styled section ends:
import chalk from 'chalk';
console.log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
console.log(
chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
)
);
Using template literals
Interpolate Chalk expressions directly in ES2015 template literals for readable multi-value log lines:
import chalk from 'chalk';
console.log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
Using console.log string substitution
Chalk-styled strings work with Node.js console.log substitution tokens:
import chalk from 'chalk';
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
// => 'Hello Sindre'
Defining reusable themes
Assign Chalk style chains to variables to create a consistent set of styles across your application. This is the recommended approach for keeping visual conventions in one place:
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange
const info = chalk.cyan;
const success = chalk.green;
console.log(error('Error: something failed'));
console.log(warning('Warning: disk space low'));
console.log(info('Info: server starting'));
console.log(success('Success: build complete'));
Using advanced colors (RGB, Hex, ANSI 256)
For terminals that support 256 or Truecolor output, use the rgb, hex, or ansi256 methods. Chalk automatically downsamples these values for terminals with lower color support:
import chalk from 'chalk';
// Hex color
console.log(chalk.hex('#DEADED').bold('Bold gray!'));
// RGB color
console.log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
// ANSI 256-color
console.log(chalk.ansi256(194)('Honeydew, more or less'));
// Background variants
console.log(chalk.bgHex('#DEADED').underline('Hello, world!'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Hello!'));
Validating style names programmatically
If you wrap Chalk and need to validate user-supplied style names, use the exported name arrays:
import { modifierNames, foregroundColorNames } from 'chalk';
console.log(modifierNames.includes('bold')); // true
console.log(foregroundColorNames.includes('pink')); // false
Basic color output
A simple hello-world demonstrating three foreground colors:
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
console.log(chalk.red('Something failed'));
console.log(chalk.green('All systems go'));
Expected output: Three lines of text — the first in blue, the second in red, the third in green.
Chained styles — bold blue text on a red background
import chalk from 'chalk';
console.log(chalk.blue.bgRed.bold('Hello world!'));
Expected output: The text Hello world! rendered bold, in blue, on a red background.
Nested styles — color within color
The outer green style resumes after the nested blue section:
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!'
)
);
Expected output: A line of green text containing a bold, underlined blue segment in the middle, after which the text returns to green.
Template literals for structured log output
Useful for dashboards or status summaries printed to the terminal:
import chalk from 'chalk';
console.log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
Expected output:
CPU: 90%
RAM: 40%
DISK: 70%
(Each value rendered in its respective color.)
Application theme with reusable style variables
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500');
const info = chalk.cyan;
const success = chalk.green;
console.log(error('Error!'));
console.log(warning('Warning!'));
console.log(info('Info'));
console.log(success('Done'));
Expected output: Four lines styled with bold red, orange, cyan, and green respectively.
Advanced colors using Hex and RGB
import chalk from 'chalk';
console.log(chalk.hex('#DEADED').bold('Bold gray!'));
console.log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
console.log(chalk.bgHex('#DEADED').underline('Background with hex color'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Inverted background'));
Expected output: Each line styled with the specified Hex or RGB color. On terminals with lower color support, Chalk automatically downsamples the color to the closest available value.
Scoped instance for a reusable module
Using a custom Chalk instance avoids affecting the global color level:
import { Chalk } from 'chalk';
const moduleChalk = new Chalk({ level: 1 }); // force basic 16-color output
export function logStatus(message) {
console.log(moduleChalk.green(message));
}
Expected output: message rendered in green using basic color support, regardless of what the host application's Chalk level is set to.
Disabling color for non-TTY output
Set level to 0 when you detect that output is being piped or redirected, so log files contain plain text:
import chalk from 'chalk';
if (!process.stdout.isTTY) {
chalk.level = 0;
}
console.log(chalk.green('This is plain text in a pipe, styled in a terminal'));
Expected output: Plain unstyled text when stdout is not a TTY (e.g., piped to a file); green text when running in an interactive terminal.
Colors do not appear — output is plain text
Symptom: Chalk calls run without errors, but the terminal shows unstyled text with no colors.
Likely cause: Chalk detected that your terminal does not support colors and set chalk.level to 0 automatically. This commonly happens when stdout is piped, redirected to a file, or when running inside a CI environment or terminal emulator with no ANSI support.
Fix: Force a color level using the FORCE_COLOR environment variable:
FORCE_COLOR=3 node your-script.js
Or set the level in code (application-level code only):
chalk.level = 3;
SyntaxError: Cannot use import statement in a module or require() of ES Module
Symptom: Your application throws a syntax or module error when importing Chalk 5.
Likely cause: Chalk 5 is ESM-only. If your project uses CommonJS (require), Node.js cannot load it with the default configuration.
Fix: Either migrate your project to ES modules by adding "type": "module" to your package.json, or install Chalk 4 which supports CommonJS:
npm install chalk@4
Then use require:
const chalk = require('chalk');
Colors show incorrectly or appear as garbled characters (e.g., \u001b[32m)
Symptom: Instead of colored text, you see raw ANSI escape sequences in the output.
Likely cause: The terminal or viewer you are using does not interpret ANSI escape codes. This commonly happens in Windows cmd.exe, certain log viewers, or editors that display raw output.
Fix: Use a terminal that supports ANSI codes. On Windows, switch to Windows Terminal. If you need to strip ANSI codes from output for logging purposes, use the strip-ansi package.
Styles in a reusable library override application-level color settings
Symptom: A module you published changes chalk.level, which unexpectedly affects the host application's Chalk output.
Likely cause: Setting chalk.level on the default export modifies a global singleton shared by all Chalk consumers in the same process.
Fix: In reusable modules, always create a scoped instance using the Chalk constructor instead of modifying the default instance:
import { Chalk } from 'chalk';
const myChalk = new Chalk({ level: 1 });
RGB or Hex colors render as a different color than expected
Symptom: You specify an RGB or Hex color, but the terminal renders a noticeably different color.
Likely cause: Your terminal does not support Truecolor (level 3) or 256-color (level 2) output. Chalk automatically downsamples colors to the nearest supported value for the detected level.
Fix: Check chalk.level to confirm your terminal's detected support level. If it is lower than expected, you can force a higher level with FORCE_COLOR=3 or verify that your terminal emulator has Truecolor enabled. Note that downsampling is by design — the output will always display something even on basic terminals.