ColorizeUsageReal-World Examples

Real-World Examples

Practical examples of using @visulima/colorize in real-world applications.

Last updated:

Real-World Examples

Practical examples demonstrating how to use @visulima/colorize in real-world scenarios.

CLI Tool Output

Build Status Reporter

import { green, red, yellow, blue, bold, dim } from "@visulima/colorize";

class BuildReporter {
    success(message: string) {
        console.log(green.bold(`✓ ${message}`));
    }

    error(message: string, details?: string) {
        console.log(red.bold(`✗ ${message}`));
        if (details) {
            console.log(dim(`  ${details}`));
        }
    }

    warning(message: string) {
        console.log(yellow(`⚠ ${message}`));
    }

    info(message: string) {
        console.log(blue(`ℹ ${message}`));
    }

    step(current: number, total: number, message: string) {
        console.log(dim(`[${current}/${total}]`) + ` ${message}`);
    }
}

const reporter = new BuildReporter();

reporter.step(1, 3, "Compiling TypeScript...");
reporter.success("TypeScript compilation completed");

reporter.step(2, 3, "Running tests...");
reporter.error("Tests failed", "2 tests failed in user.test.ts");

reporter.step(3, 3, "Building bundle...");
reporter.warning("Bundle size exceeds 1MB");
reporter.success("Build completed");

Package Manager Output

import { green, cyan, yellow, gray, bold } from "@visulima/colorize";

function installPackage(name: string, version: string) {
    console.log(bold(`Installing ${name}@${version}...`));
    console.log(gray(`  → Resolving dependencies`));
    console.log(gray(`  → Fetching packages`));
    console.log(gray(`  → Linking dependencies`));
    console.log(green(`  ✓ ${name}@${version} installed`));
}

function packageInfo(name: string, description: string) {
    console.log(cyan.bold(name));
    console.log(gray(description));
}

installPackage("@visulima/colorize", "2.0.0");
packageInfo("@visulima/colorize", "Terminal string styling done right");

Structured Logging

Logger with Log Levels

import { gray, cyan, yellow, red, bold } from "@visulima/colorize";

enum LogLevel {
    DEBUG = 0,
    INFO = 1,
    WARN = 2,
    ERROR = 3,
}

class Logger {
    constructor(private level: LogLevel = LogLevel.INFO) {}

    debug(message: string, data?: any) {
        if (this.level <= LogLevel.DEBUG) {
            console.log(gray(`[DEBUG] ${message}`), data || "");
        }
    }

    info(message: string, data?: any) {
        if (this.level <= LogLevel.INFO) {
            console.log(cyan(`[INFO]  ${message}`), data || "");
        }
    }

    warn(message: string, data?: any) {
        if (this.level <= LogLevel.WARN) {
            console.log(yellow(`[WARN]  ${message}`), data || "");
        }
    }

    error(message: string, error?: Error) {
        if (this.level <= LogLevel.ERROR) {
            console.log(red.bold(`[ERROR] ${message}`));
            if (error) {
                console.log(red(error.stack || error.message));
            }
        }
    }

    success(message: string) {
        console.log(green.bold(`[OK]    ${message}`));
    }
}

// Usage
const logger = new Logger(LogLevel.DEBUG);

logger.debug("Application starting");
logger.info("Server listening on port 3000");
logger.warn("Deprecated API usage detected");
logger.error("Database connection failed", new Error("Connection timeout"));
logger.success("All migrations completed");

Request Logger

import { green, yellow, red, cyan, gray, bold } from "@visulima/colorize";

interface RequestLog {
    method: string;
    path: string;
    status: number;
    duration: number;
}

function logRequest({ method, path, status, duration }: RequestLog) {
    const methodColor = {
        GET: cyan,
        POST: green,
        PUT: yellow,
        DELETE: red,
        PATCH: yellow,
    }[method] || gray;

    const statusColor = status >= 500 ? red : status >= 400 ? yellow : status >= 300 ? cyan : green;

    console.log(
        methodColor.bold(method.padEnd(6)) +
            gray(path.padEnd(30)) +
            statusColor(status.toString().padEnd(5)) +
            gray(`${duration}ms`),
    );
}

// Usage
logRequest({ method: "GET", path: "/api/users", status: 200, duration: 45 });
logRequest({ method: "POST", path: "/api/users", status: 201, duration: 120 });
logRequest({ method: "GET", path: "/api/posts", status: 404, duration: 12 });
logRequest({ method: "PUT", path: "/api/users/123", status: 500, duration: 2500 });

Terminal Dashboards

System Monitor

import { green, red, yellow, hex, inverse, bold } from "@visulima/colorize";

interface SystemStats {
    cpu: number;
    memory: { used: number; total: number };
    disk: { used: number; total: number };
}

function displaySystemStats(stats: SystemStats) {
    const cpuColor = stats.cpu > 80 ? red : stats.cpu > 50 ? yellow : green;
    const memPercent = (stats.memory.used / stats.memory.total) * 100;
    const memColor = memPercent > 80 ? red : memPercent > 50 ? yellow : green;
    const diskPercent = (stats.disk.used / stats.disk.total) * 100;
    const diskColor = diskPercent > 80 ? red : diskPercent > 50 ? yellow : green;

    console.log(inverse(bold(" SYSTEM MONITOR ")));
    console.log();
    console.log(`CPU:  ${cpuColor`${stats.cpu.toFixed(1)}%`}`.padEnd(20) + createProgressBar(stats.cpu, 100));
    console.log(
        `RAM:  ${memColor`${memPercent.toFixed(1)}%`}`.padEnd(20) +
            createProgressBar(stats.memory.used, stats.memory.total),
    );
    console.log(
        `DISK: ${diskColor`${diskPercent.toFixed(1)}%`}`.padEnd(20) +
            createProgressBar(stats.disk.used, stats.disk.total),
    );
}

function createProgressBar(current: number, total: number, width: number = 20): string {
    const percent = current / total;
    const filled = Math.round(width * percent);
    const empty = width - filled;
    const bar = "█".repeat(filled) + "░".repeat(empty);

    return percent > 0.8 ? red(bar) : percent > 0.5 ? yellow(bar) : green(bar);
}

// Usage
displaySystemStats({
    cpu: 65.4,
    memory: { used: 8.2, total: 16 },
    disk: { used: 120, total: 256 },
});

Progress Indicators

import { green, blue, yellow, gray } from "@visulima/colorize";

class ProgressBar {
    private current: number = 0;

    constructor(
        private total: number,
        private width: number = 40,
    ) {}

    update(current: number, message?: string) {
        this.current = current;
        this.render(message);
    }

    private render(message?: string) {
        const percent = Math.min(100, (this.current / this.total) * 100);
        const filled = Math.round((this.width * percent) / 100);
        const empty = this.width - filled;

        const bar = green("█".repeat(filled)) + gray("░".repeat(empty));
        const percentText = blue(`${percent.toFixed(1)}%`);
        const status = message ? yellow(` ${message}`) : "";

        process.stdout.write(`\r${bar} ${percentText}${status}`);

        if (this.current >= this.total) {
            console.log(); // New line when complete
        }
    }
}

// Usage
const progress = new ProgressBar(100);

let current = 0;
const interval = setInterval(() => {
    current += 5;
    progress.update(current, `Processing item ${current}...`);

    if (current >= 100) {
        clearInterval(interval);
    }
}, 100);

File Operations

File Tree Display

import { blue, green, yellow, gray } from "@visulima/colorize";

interface FileNode {
    name: string;
    type: "file" | "directory";
    children?: FileNode[];
}

function displayTree(node: FileNode, prefix: string = "", isLast: boolean = true) {
    const connector = isLast ? "└── " : "├── ";
    const color = node.type === "directory" ? blue.bold : green;
    const icon = node.type === "directory" ? "📁" : "📄";

    console.log(gray(prefix + connector) + icon + " " + color(node.name));

    if (node.children) {
        const childPrefix = prefix + (isLast ? "    " : "│   ");
        node.children.forEach((child, index) => {
            const isLastChild = index === node.children!.length - 1;
            displayTree(child, childPrefix, isLastChild);
        });
    }
}

// Usage
const tree: FileNode = {
    name: "project",
    type: "directory",
    children: [
        {
            name: "src",
            type: "directory",
            children: [
                { name: "index.ts", type: "file" },
                { name: "utils.ts", type: "file" },
            ],
        },
        { name: "package.json", type: "file" },
        { name: "README.md", type: "file" },
    ],
};

displayTree(tree);

File Diff Display

import { green, red, gray } from "@visulima/colorize";

interface DiffLine {
    type: "add" | "remove" | "unchanged";
    content: string;
}

function displayDiff(lines: DiffLine[]) {
    lines.forEach((line) => {
        switch (line.type) {
            case "add":
                console.log(green(`+ ${line.content}`));
                break;
            case "remove":
                console.log(red(`- ${line.content}`));
                break;
            case "unchanged":
                console.log(gray(`  ${line.content}`));
                break;
        }
    });
}

// Usage
const diff: DiffLine[] = [
    { type: "unchanged", content: "function hello() {" },
    { type: "remove", content: '  console.log("Hello");' },
    { type: "add", content: '  console.log("Hello World");' },
    { type: "unchanged", content: "}" },
];

displayDiff(diff);

Test Runners

Test Results Display

import { green, red, yellow, gray, bold } from "@visulima/colorize";

interface TestResult {
    name: string;
    status: "pass" | "fail" | "skip";
    duration: number;
    error?: string;
}

interface TestSuite {
    name: string;
    tests: TestResult[];
}

function displayTestResults(suite: TestSuite) {
    console.log(bold(`\n${suite.name}`));

    suite.tests.forEach((test) => {
        const icon = test.status === "pass" ? green("✓") : test.status === "fail" ? red("✗") : yellow("○");

        const duration = gray(`(${test.duration}ms)`);

        console.log(`  ${icon} ${test.name} ${duration}`);

        if (test.error) {
            console.log(red(`    ${test.error}`));
        }
    });

    const passed = suite.tests.filter((t) => t.status === "pass").length;
    const failed = suite.tests.filter((t) => t.status === "fail").length;
    const skipped = suite.tests.filter((t) => t.status === "skip").length;

    console.log();
    console.log(bold("Summary:"));
    console.log(`  ${green(`Passed: ${passed}`)}`);
    if (failed > 0) console.log(`  ${red(`Failed: ${failed}`)}`);
    if (skipped > 0) console.log(`  ${yellow(`Skipped: ${skipped}`)}`);
}

// Usage
displayTestResults({
    name: "User Service Tests",
    tests: [
        { name: "should create user", status: "pass", duration: 45 },
        { name: "should validate email", status: "pass", duration: 12 },
        { name: "should reject invalid email", status: "fail", duration: 8, error: "Expected false but got true" },
        { name: "should update user", status: "skip", duration: 0 },
    ],
});

Interactive Prompts

Question Prompt

import { cyan, green, yellow } from "@visulima/colorize";
import * as readline from "readline";

async function ask(question: string): Promise<string> {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });

    return new Promise((resolve) => {
        rl.question(cyan(`? ${question} `), (answer) => {
            rl.close();
            resolve(answer);
        });
    });
}

async function confirm(question: string): Promise<boolean> {
    const answer = await ask(`${question} ${yellow("(y/n)")}`);
    return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
}

// Usage
async function runInteractive() {
    const name = await ask("What is your name?");
    console.log(green(`Hello, ${name}!`));

    const proceed = await confirm("Do you want to continue?");
    if (proceed) {
        console.log(green("Continuing..."));
    } else {
        console.log(yellow("Cancelled"));
    }
}

Next Steps

Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues