Black and white terminal output can be functional, but adding color creates a better user experience with improved readability, visual hierarchy, and an overall more polished look. If you're building Node.js command-line applications, the Chalk library makes it incredibly simple to add vibrant colors and styling to your terminal output.
In this guide, we'll explore how to implement Chalk in your Node.js applications, from basic usage to advanced techniques that will help your CLI tools stand out.
Before diving into implementation, let's understand why colored terminal output matters:
Chalk is a popular Node.js library that simplifies the process of adding colors and styles to terminal output. It has a clean, expressive API and is highly performant.
First, let's install Chalk in your Node.js project:
npm install chalk
Note: As of 2025, we recommend using Chalk 5.x or later, which is ESM-only. If you're working with CommonJS modules, you may need to use Chalk 4.x or implement a workaround.
Let's start with a simple example to demonstrate Chalk's capabilities:
// app.js
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
console.log(chalk.red.bold('Error:') + ' Something went wrong');
console.log(chalk.green('Success:') + ' Operation completed');
console.log(chalk.yellow.underline('Warning:') + ' Resource usage is high');
Run this script, and you'll see your terminal light up with colored text. The API is intuitive – just chain the color and style methods before your string.
Chalk offers a wide range of colors and styles that you can combine to create the perfect look for your CLI application.
Basic colors include:
black
red
green
yellow
blue
magenta
cyan
white
gray
(or grey
)Each of these has a "bright" version, accessible by prefixing with bright
, like brightRed
or brightBlue
.
Beyond colors, Chalk provides several text styling options:
bold
- Bold textdim
- Dimmed textitalic
- Italic text (not widely supported)underline
- Underlined textinverse
- Inverted background and foreground colorshidden
- Hidden text (useful for passwords)strikethrough
- Struck-through textYou can also set background colors using the bg
prefix:
console.log(chalk.black.bgWhite(' INVERSE '));
console.log(chalk.bgGreen(' SUCCESS ') + ' Operation completed');
console.log(chalk.bgRed.white.bold(' ERROR ') + ' Critical system failure');
Now that we understand the basics, let's explore some more advanced ways to use Chalk in your Node.js applications.
For consistent styling across your application, create a theme module:
// theme.js
import chalk from 'chalk';
export const theme = {
info: chalk.blue,
success: chalk.green.bold,
warning: chalk.yellow,
error: chalk.red.bold,
highlight: chalk.magenta.underline,
muted: chalk.gray,
title: chalk.cyan.bold.underline,
json: chalk.cyan,
prompt: chalk.green.bold,
};
Then import and use it throughout your application:
// logger.js
import { theme } from './theme.js';
export function log(message, type = 'info') {
const styles = {
info: () => console.log(theme.info('ℹ') + ' ' + message),
success: () => console.log(theme.success('✓') + ' ' + message),
warning: () => console.log(theme.warning('⚠') + ' ' + message),
error: () => console.log(theme.error('✗') + ' ' + message),
};
(styles[type] || styles.info)();
}
Chalk allows you to nest styles for more complex formatting:
const nested = chalk.red.bold('Error') +
chalk.white(': cannot find module ') +
chalk.yellow.underline('./some-file.js');
console.log(nested);
For more complex strings with multiple styles, template literals are particularly useful:
console.log(chalk`
{bold.red Error}: The operation failed
{green.underline Details}:
- Status: {yellow 404}
- Message: {italic Resource not found}
`);
You can programmatically determine colors based on data values:
function logPerformance(metricName, value, threshold) {
const color = value > threshold ? chalk.red : chalk.green;
console.log(`${metricName}: ${color(value)}ms`);
}
logPerformance('Response time', 120, 100);
logPerformance('Database query', 50, 100);
Let's combine these techniques to create a simple CLI dashboard for monitoring system resources:
// monitor.js
import chalk from 'chalk';
function getRandomValue(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getColorForUsage(percentage) {
if (percentage < 60) return chalk.green;
if (percentage < 80) return chalk.yellow;
return chalk.red;
}
function createBar(percentage, width = 30) {
const completed = Math.floor((width * percentage) / 100);
const remaining = width - completed;
const colorFn = getColorForUsage(percentage);
return colorFn('█'.repeat(completed)) + chalk.gray('░'.repeat(remaining));
}
function displayDashboard() {
console.clear();
const cpu = getRandomValue(30, 95);
const memory = getRandomValue(40, 85);
const disk = getRandomValue(20, 70);
const network = getRandomValue(10, 60);
console.log(chalk.bold.underline('\n System Monitor \n'));
console.log(`${chalk.blue('CPU Usage: ')} ${createBar(cpu)} ${getColorForUsage(cpu)(`${cpu}%`)}`);
console.log(`${chalk.magenta('Memory Usage: ')} ${createBar(memory)} ${getColorForUsage(memory)(`${memory}%`)}`);
console.log(`${chalk.cyan('Disk Space: ')} ${createBar(disk)} ${getColorForUsage(disk)(`${disk}%`)}`);
console.log(`${chalk.yellow('Network I/O: ')} ${createBar(network)} ${getColorForUsage(network)(`${network}%`)}`);
console.log('\n' + chalk.gray('Last updated: ' + new Date().toLocaleTimeString()));
console.log(chalk.dim('Press Ctrl+C to exit'));
}
// Update every second
setInterval(displayDashboard, 1000);
displayDashboard();
This creates a live-updating dashboard with colored bars that change based on usage levels.
While most modern terminals support a wide range of ANSI colors and styles, some terminals have limitations. Chalk automatically detects terminal capabilities and degrades gracefully when needed.
If you want to enforce a specific level of color support, you can do so with the level
option:
import chalk from 'chalk';
// Force color level (0-3)
// Level 0: No colors
// Level 1: Basic colors
// Level 2: 256 colors
// Level 3: Truecolor (16 million colors)
chalk.level = 2;
Prior to Chalk 5.x, Windows terminals had limited color support. However, modern Windows terminals (Windows Terminal, VS Code's integrated terminal) now offer excellent color support. If you're targeting older Windows environments, you may need to consider compatibility.
When using colors in your CLI applications, keep these best practices in mind:
While Chalk is the most popular option, there are alternatives worth considering:
Each has its own advantages, but Chalk remains the most widely used due to its balance of features, performance, and ease of use.
If you're building more complex command-line applications, Chalk integrates well with popular CLI frameworks:
import { Command } from 'commander';
import chalk from 'chalk';
const program = new Command();
program
.name('awesome-tool')
.description('A CLI tool with colorful output')
.version('1.0.0');
program
.command('process')
.description('Process some data')
.action(() => {
console.log(chalk.green('Processing data...'));
// Do work here
console.log(chalk.green.bold('✓') + ' Processing complete!');
});
program.parse();
import inquirer from 'inquirer';
import chalk from 'chalk';
const questions = [
{
type: 'input',
name: 'name',
message: chalk.blue('What is your name?'),
default: 'User',
},
{
type: 'list',
name: 'theme',
message: chalk.blue('Choose a theme:'),
choices: [
`${chalk.bold.green('Light')} - For bright environments`,
`${chalk.bold.magenta('Dark')} - For dark environments`,
`${chalk.bold.yellow('High Contrast')} - For accessibility`,
],
},
];
inquirer.prompt(questions).then((answers) => {
console.log(chalk.green('\nThank you!'));
console.log(chalk.cyan('Your settings:'));
console.log(JSON.stringify(answers, null, 2));
});
Adding color to your Node.js terminal applications is a small investment that yields significant improvements in user experience. Chalk provides an elegant, powerful API that makes it easy to implement colorful, styled terminal output that helps your CLI tools stand out.
Whether you're building developer tools, system utilities, or interactive applications, thoughtful use of color can enhance readability, establish visual hierarchy, and create a more polished, professional feel.
Start with simple color additions for different message types, then progress to more complex styling as your application grows. Remember to maintain consistency and consider accessibility as you design your terminal UI.
With the techniques covered in this guide, you're well-equipped to create terminal applications that are not just functional, but also visually engaging and user-friendly.
Happy coding!
Start your journey with us today and get access to our resources and tools.