New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

color-printf

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

color-printf

A lightweight terminal color printing tool with ESM and CommonJS support, providing printf-style formatting and color functions

latest
npmnpm
Version
1.1.4
Version published
Maintainers
1
Created
Source

color-printf

A lightweight, highly compatible terminal color printing tool that supports both ESM and CommonJS module systems. It provides convenient color functions (e.g., red("text")), custom hex colors, printf-style formatting, and string formatting (color.format) — no manual ANSI escape code handling required, with support for most terminals.

🌟 Core Features

  • Dual Module Support: Seamlessly compatible with ESM (import) and CommonJS (require).
  • Two Functional Modes:
    • color.printf(): Directly prints colored text to the terminal.
    • color.format(): Returns a color-formatted string for custom output (e.g., with console.log).
  • Intuitive Usage: Call color functions directly (e.g., red(), green()) without complex syntax.
  • Flexible Color Options: Supports color names (e.g., red), hex colors (e.g., #ff0000 or #f00), and case insensitivity.
  • printf-Style Formatting: Works with format specifiers like %s, %d, and %j.
  • Terminal Adaptability: Automatically detects 24-bit true color support; falls back to 8-bit colors for older terminals.
  • Friendly Syntax: No trailing # required; supports both English (:) and Chinese () colons to separate colors from text.

📦 Installation

Prerequisites

  • Node.js ≥ 14 (supports mixed ESM/CommonJS usage)

Install the Package

# Install via npm
npm install color-printf --save

# Install via yarn
yarn add color-printf

🚀 Quick Start

Choose the import method based on your project’s module system and explore core features:

// Import on demand (recommended)
import { red, color } from 'color-printf';

// 1. Convenient color functions: Direct printing
red("This is red text");

// 2. color.printf(): Directly print multi-colored text
color.printf("##ffff00: Yellow background text #0000ff: Blue text");

// 3. color.format(): Generate colored string for custom printing
const coloredStr = color.format("#ff00ff: Purple text with %s", "format parameter");
console.log(coloredStr); // Manually output with console.log

2. CommonJS Import (For traditional Node.js projects without "type": "module")

// Import on demand
const { green, color } = require('color-printf');

// 1. Convenient color functions
green("This is green text with formatting: %d", 123);

// 2. color.printf()
color.printf("#red: Error message ##yellow: Warning content");

// 3. color.format()
const mixedStr = color.format("##00ff00: Green background, #ff8800: Orange text");
console.log(mixedStr); // Custom output timing

📋 Detailed Usage

1. Convenient Color Functions

Directly call pre-defined color functions for quick single-color text printing with format support:

TypeFunction NameDescriptionExample
Foregroundblack()Black textblack("Black text with %s", "parameter")
red()Red textred("Error: Operation failed")
green()Green textgreen("Success: Data saved")
yellow()Yellow textyellow("Warning: Low disk space")
blue()Blue textblue("Info: Loading...")
magenta()Magenta textmagenta("Debug: Parameter value")
cyan()Cyan textcyan("Log: Request time")
gray()gray textgray("Log: Request time")
white()White textwhite("Highlight: Important content")
BackgroundbgBlack()Black backgroundbgBlack("Text on black background")
bgRed()Red backgroundbgRed("Urgent error: Text on red")
bgGreen()Green backgroundbgGreen("Success: Text on green")
bgYellow()Yellow backgroundbgYellow("Note: Text on yellow")
bgBlue()Blue backgroundbgBlue("Info: Text on blue")
bgMagenta()Magenta backgroundbgMagenta("Debug: Text on magenta")
bgCyan()Cyan backgroundbgCyan("Log: Text on cyan")
bgWhite()White backgroundbgWhite("Emphasis: Text on white")
bgGray()gray backgroundbgGray("Emphasis: Text on white")

2. color.printf(): Direct Multi-Color Printing

Supports mixed colors and custom hex colors with these syntax rules:

  • Foreground color: #color-value: text-content (color-value = name or hex)
  • Background color: ##color-value: text-content (double # for background)
  • Separator: Use either English (:) or Chinese () colon to separate color and text
  • Trailing #: Not required — color applies until next marker or end of text

Example: Mixed Colors with Formatting

import { color } from 'color-printf';

// 1. Custom hex colors
color.printf("#1E90FF: Sky blue text (6-digit hex) ##f00: Red background text");

// 2. Mixed colors + format specifiers
color.printf(
  "#red: Error ##yellow: Warning #blue: User %s submitted %d items",
  "John Doe",
  5
);

// 3. Compatibility with Chinese colon
color.printf("#green:Success text with Chinese colon ##ff8800:Text on orange background");

3. color.format(): Generate Colored Strings

Returns a string with ANSI color codes without printing, giving you control over output timing (e.g., with console.log, logging systems, etc.).

Basic Usage

import { color } from 'color-printf';

// 1. Generate single-color string
const redStr = color.format("#ff0000: This is a red string");
console.log(redStr); // Manual printing

// 2. Generate multi-color string
const mixedStr = color.format("##ffff00: Yellow background #0000ff: Blue text with %s", "parameter");
console.log(mixedStr); // Output with console.log

// 3. Integrate with logging tools
// logger.info(color.format("#00ff00: Log message: %j", { code: 200 })); // Example: logging system

Difference Between color.format() and color.printf()

MethodBehaviorUse Cases
color.printf()Directly prints to terminalSimple scenarios, no custom logic
color.format()Returns colored stringCustom output (logging systems, delayed printing)

4. Supported Format Specifiers

Fully compatible with Node.js util.format() — supports all standard specifiers:

SpecifierDescriptionExample
%sStringred("Username: %s", "admin")
%dNumber (integer/float)green("Score: %d", 95.5)
%jJSON (objects/arrays)blue("Config: %j", { theme: "dark" })
%%Escape for percent signyellow("Completion: %d%%", 80)
%oDetailed object (with prototype)magenta("Object details: %o", new Date())

🔧 API Reference

1. Convenient Color Functions (e.g., red(format, ...args))

  • Purpose: Directly prints text in specified color with formatting support.
  • Parameters:
    • format: String or format template (e.g., "Error: %s").
    • ...args: Optional — values to replace format specifiers.
  • Return Value: None (prints directly to terminal).

2. color.printf(format, ...args)

  • Purpose: Parses color-marked format string and prints directly to terminal.
  • Parameters:
    • format: Color-marked format template (e.g., "#ff0000: Error: %s").
    • ...args: Optional — values to replace format specifiers.
  • Return Value: None (prints directly to terminal).

3. color.format(format, ...args)

  • Purpose: Parses color-marked format string and returns string with ANSI color codes.
  • Parameters:
    • format: Color-marked format template (e.g., "##ffff00: Yellow background text").
    • ...args: Optional — values to replace format specifiers.
  • Return Value: string (formatted string with ANSI color codes).

🖥️ Terminal Compatibility

Terminal TypeSupport StatusNotes
Windows Terminal✅ Full Support (24-bit true color)Recommended
VS Code Terminal✅ Full Support (24-bit true color)No extra configuration needed
iTerm2 (macOS)✅ Full Support (24-bit true color)Recommended
Linux Terminal (gnome-terminal)✅ Full Support (24-bit true color)-
Windows CMD⚠️ Partial Support (8-bit colors)Enable ANSI support (see below)

Enabling ANSI Support for Windows CMD

  • Open CMD as Administrator.
  • Run this command (persists across sessions):
    reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
    
  • Restart CMD to apply changes.

❓ Frequently Asked Questions

Q1: Why isn't the string from color.format() showing colors?

  • Ensure your terminal supports ANSI escape codes (use Windows Terminal, VS Code Terminal, or iTerm2 for best results).
  • Check color syntax: Always use a colon (: or ) to separate color and text (e.g., #red: text not #red text).
  • Verify your output method isn't stripping ANSI codes (some logging plugins require configuration to preserve escape codes).

Q2: How to resolve module import errors?

  • ESM Errors: Ensure your project’s package.json includes "type": "module", or use .mjs file extensions.
  • CommonJS Errors: Avoid import in CommonJS projects — use require instead. For mixed usage, use dynamic import (Node.js ≥ 14.8):
    // Dynamic import in CommonJS
    import('color-printf').then(({ red, color }) => {
      red("Red text via dynamic import");
      console.log(color.format("#ff00ff: Purple text generated dynamically"));
    });
    

Q3: How to mix foreground and background colors?

Nest color markers in color.printf() or color.format() (background first, then foreground):

// Red text on yellow background (direct print)
color.printf("##ffff00:#ff0000: Red text on yellow background");

// Red text on yellow background (generated string)
const mixedColorStr = color.format("##ffff00:#ff0000: Red text on yellow background");
console.log(mixedColorStr);

📄 License

MIT License | Free for personal and commercial use. Modification and distribution permitted with attribution to the original author.

Keywords

color

FAQs

Package last updated on 06 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts