Built-in terminal color capability detection and metadata for understanding and working with different terminal environments.
Automatic detection of terminal color capabilities with detailed information about supported features.
/**
* Color support information for stdout stream
* Contains level and capability flags, or false if no color support
*/
const supportsColor: ColorInfo;
/**
* Color support information for stderr stream
* Contains level and capability flags, or false if no color support
*/
const supportsColorStderr: ColorInfo;
type ColorInfo = ColorSupport | false;
interface ColorSupport {
/** The detected color support level (0-3) */
level: ColorSupportLevel;
/** Whether basic 16 colors are supported */
hasBasic: boolean;
/** Whether ANSI 256 colors are supported */
has256: boolean;
/** Whether Truecolor 16 million colors are supported */
has16m: boolean;
}
type ColorSupportLevel = 0 | 1 | 2 | 3;Usage Examples:
import { supportsColor, supportsColorStderr } from 'chalk';
// Check stdout color support
if (supportsColor) {
console.log('stdout color support detected:');
console.log(' Level:', supportsColor.level);
console.log(' Basic colors:', supportsColor.hasBasic);
console.log(' 256 colors:', supportsColor.has256);
console.log(' Truecolor:', supportsColor.has16m);
} else {
console.log('No stdout color support detected');
}
// Check stderr color support
if (supportsColorStderr) {
console.log('stderr color support detected:');
console.log(' Level:', supportsColorStderr.level);
console.log(' Basic colors:', supportsColorStderr.hasBasic);
console.log(' 256 colors:', supportsColorStderr.has256);
console.log(' Truecolor:', supportsColorStderr.has16m);
} else {
console.log('No stderr color support detected');
}Pre-configured Chalk instance specifically for stderr output with appropriate color detection.
/**
* Chalk instance configured for stderr stream
* Uses stderr-specific color detection instead of stdout
*/
const chalkStderr: ChalkInstance;Usage Examples:
import chalk, { chalkStderr } from 'chalk';
// Regular stdout output
console.log(chalk.blue('This goes to stdout'));
// Stderr output with appropriate color detection
console.error(chalkStderr.red('This goes to stderr'));
// Different streams may have different color support
if (chalkStderr.level !== chalk.level) {
console.log(`stdout level: ${chalk.level}, stderr level: ${chalkStderr.level}`);
}Understanding what each color support level provides:
import { supportsColor } from 'chalk';
function describeColorLevel(colorInfo) {
if (!colorInfo) {
return 'No color support - all colors will be stripped';
}
switch (colorInfo.level) {
case 0:
return 'Level 0: All colors disabled';
case 1:
return 'Level 1: Basic 16 colors (8 standard + 8 bright variants)';
case 2:
return 'Level 2: ANSI 256 colors (216 colors + 24 grayscale)';
case 3:
return 'Level 3: Truecolor 16 million colors (full RGB)';
default:
return 'Unknown color level';
}
}
console.log('Current color support:', describeColorLevel(supportsColor));How Chalk detects color support and environment-specific behavior:
import { supportsColor } from 'chalk';
// Display detection information
console.log('Environment color detection:');
console.log('NODE_ENV:', process.env.NODE_ENV);
console.log('TERM:', process.env.TERM);
console.log('COLORTERM:', process.env.COLORTERM);
console.log('CI:', process.env.CI);
console.log('NO_COLOR:', process.env.NO_COLOR);
console.log('FORCE_COLOR:', process.env.FORCE_COLOR);
if (supportsColor) {
console.log('\nDetected capabilities:');
console.log('- Basic 16 colors:', supportsColor.hasBasic);
console.log('- 256 colors:', supportsColor.has256);
console.log('- Truecolor (16m):', supportsColor.has16m);
console.log('- Final level:', supportsColor.level);
}Environment variables that affect color detection:
import chalk from 'chalk';
// Examples of environment variable effects
console.log('Environment variable examples:');
// NO_COLOR - disables colors entirely (standard)
console.log('NO_COLOR=1 - disables all colors');
// FORCE_COLOR - forces specific color level
console.log('FORCE_COLOR=0 - force disable colors');
console.log('FORCE_COLOR=1 - force basic 16 colors');
console.log('FORCE_COLOR=2 - force 256 colors');
console.log('FORCE_COLOR=3 - force truecolor');
// Command line flags
console.log('--color - enable colors');
console.log('--no-color - disable colors');
console.log('--color=256 - force 256-color mode');
console.log('--color=16m - force truecolor mode');Common patterns for working with color support detection:
import chalk, { supportsColor } from 'chalk';
// Adapt output based on color support
function createAdaptiveLogger() {
if (!supportsColor) {
// No color support - use symbols and formatting
return {
success: (msg) => `✓ ${msg}`,
warning: (msg) => `⚠ ${msg}`,
error: (msg) => `✗ ${msg}`,
info: (msg) => `ℹ ${msg}`
};
}
if (supportsColor.level === 1) {
// Basic colors only
return {
success: (msg) => chalk.green(`✓ ${msg}`),
warning: (msg) => chalk.yellow(`⚠ ${msg}`),
error: (msg) => chalk.red(`✗ ${msg}`),
info: (msg) => chalk.blue(`ℹ ${msg}`)
};
}
// Advanced colors available
return {
success: (msg) => chalk.hex('#28A745')(`✓ ${msg}`),
warning: (msg) => chalk.hex('#FFC107')(`⚠ ${msg}`),
error: (msg) => chalk.hex('#DC3545')(`✗ ${msg}`),
info: (msg) => chalk.hex('#007BFF')(`ℹ ${msg}`)
};
}
const logger = createAdaptiveLogger();
console.log(logger.success('Operation completed'));
console.log(logger.warning('Check configuration'));
console.log(logger.error('Something went wrong'));
console.log(logger.info('Additional information'));import { supportsColor } from 'chalk';
// Feature-based color usage
class TerminalRenderer {
constructor() {
this.colorSupport = supportsColor;
}
canUseColors() {
return Boolean(this.colorSupport);
}
canUse256Colors() {
return this.colorSupport && this.colorSupport.has256;
}
canUseTruecolor() {
return this.colorSupport && this.colorSupport.has16m;
}
renderProgressBar(progress, options = {}) {
const width = options.width || 20;
const filled = Math.floor((progress / 100) * width);
const empty = width - filled;
if (this.canUseTruecolor()) {
// Use gradient colors for truecolor terminals
const filledBar = chalk.rgb(0, 255, 0)('█'.repeat(filled));
const emptyBar = chalk.rgb(64, 64, 64)('░'.repeat(empty));
return `[${filledBar}${emptyBar}] ${progress}%`;
}
if (this.canUse256Colors()) {
// Use 256-color palette
const filledBar = chalk.ansi256(46)('█'.repeat(filled));
const emptyBar = chalk.ansi256(240)('░'.repeat(empty));
return `[${filledBar}${emptyBar}] ${progress}%`;
}
if (this.canUseColors()) {
// Use basic colors
const filledBar = chalk.green('█'.repeat(filled));
const emptyBar = chalk.gray('░'.repeat(empty));
return `[${filledBar}${emptyBar}] ${progress}%`;
}
// No colors - use ASCII
const filledBar = '='.repeat(filled);
const emptyBar = '-'.repeat(empty);
return `[${filledBar}${emptyBar}] ${progress}%`;
}
}
const renderer = new TerminalRenderer();
console.log(renderer.renderProgressBar(75));
console.log('Terminal capabilities:');
console.log('- Colors:', renderer.canUseColors());
console.log('- 256 colors:', renderer.canUse256Colors());
console.log('- Truecolor:', renderer.canUseTruecolor());import chalk, { chalkStderr, supportsColor, supportsColorStderr } from 'chalk';
// Handle stdout and stderr differently
class StreamAwareLogger {
constructor() {
this.stdout = chalk;
this.stderr = chalkStderr;
}
log(message) {
// Regular log to stdout
console.log(this.stdout.blue(`[LOG] ${message}`));
}
error(message) {
// Error to stderr with appropriate color support
console.error(this.stderr.red(`[ERROR] ${message}`));
}
getStreamInfo() {
return {
stdout: {
supported: Boolean(supportsColor),
level: supportsColor ? supportsColor.level : 0
},
stderr: {
supported: Boolean(supportsColorStderr),
level: supportsColorStderr ? supportsColorStderr.level : 0
}
};
}
}
const logger = new StreamAwareLogger();
logger.log('This is a regular log message');
logger.error('This is an error message');
console.log('Stream color support:', logger.getStreamInfo());Utilities for testing color output across different support levels:
import { Chalk } from 'chalk';
// Test function to see how colors appear at different levels
function testColorSupport() {
const testText = 'Color Test';
const levels = [0, 1, 2, 3];
console.log('Testing color support across levels:\n');
levels.forEach(level => {
const testChalk = new Chalk({ level });
console.log(`Level ${level}:`);
console.log(' Basic:', testChalk.red(testText));
console.log(' RGB:', testChalk.rgb(255, 128, 0)(testText));
console.log(' HEX:', testChalk.hex('#8A2BE2')(testText));
console.log(' 256:', testChalk.ansi256(201)(testText));
console.log('');
});
}
// Run the test
testColorSupport();