API Reference

Complete API documentation for @visulima/fmt

Last updated:

API Reference

Complete reference for all functions and types in the @visulima/fmt package.

Main Functions

format

Format a string using printf-style placeholders.

Signature:

function format(
  fmt: string,
  parameters: unknown[],
  options?: FormatOptions
): string

Parameters:

  • fmt (string, required) - Format string with placeholders (e.g., "Hello %s")
  • parameters (unknown[], required) - Array of values to substitute
  • options (FormatOptions, optional) - Formatting options

Returns: string - Formatted string

Example:

import { format } from "@visulima/fmt";

const result = format("Hello %s, you have %d messages", ["Alice", 5]);
console.log(result); // "Hello Alice, you have 5 messages"

build

Build a custom format function with additional formatters.

Signature:

function build(options: BuildOptions): FormatFunction

Parameters:

  • options (BuildOptions, required) - Configuration options
    • formatters (Formatters, optional) - Custom format specifiers

Returns: FormatFunction - A custom format function

Example:

import { build } from "@visulima/fmt";

const format = build({
  formatters: {
    t: (time) => new Date(time).toLocaleString(),
    h: (num) => `0x${num.toString(16)}`
  }
});

const result = format("Time: %t, Hex: %h", [Date.now(), 255]);
// Time: 2/16/2026, 12:30:00 PM, Hex: 0xff

Types

FormatOptions

Options for the format function.

Type Definition:

interface FormatOptions {
  stringify?: (value: unknown) => string;
}

Properties:

  • stringify (function, optional) - Custom serializer for %j placeholder

Example:

import { format } from "@visulima/fmt";

const options = {
  stringify: (obj: unknown) => JSON.stringify(obj, null, 2)
};

const result = format("Config: %j", [{ port: 8080 }], options);

BuildOptions

Options for the build function.

Type Definition:

interface BuildOptions {
  formatters?: Formatters;
}

Properties:

  • formatters (Formatters, optional) - Custom format specifiers

Formatters

Custom formatter functions.

Type Definition:

type Formatters = Record<string, (value: any) => string>;

Description: An object mapping single-character keys to formatter functions.

Example:

const formatters: Formatters = {
  u: (url) => new URL(url).hostname,
  p: (percent) => `${(percent * 100).toFixed(2)}%`
};

FormatFunction

The function signature returned by build.

Type Definition:

type FormatFunction = (
  fmt: string,
  parameters: unknown[],
  options?: FormatOptions
) => string;

Description: Same signature as format but with custom formatters baked in.


Format Specifiers

Standard Specifiers

SpecifierDescriptionExample
%sStringformat("%s", ["hello"])"hello"
%dDecimal numberformat("%d", [42])"42"
%iIntegerformat("%i", [42.7])"42"
%fFloatformat("%f", [3.14])"3.14"
%jJSONformat("%j", [{a:1}])'{"a":1}'
%oObjectformat("%o", [{a:1}])'{a: 1}'
%OObject (detailed)format("%O", [obj]) → includes non-enumerable
%cCSS stylingformat("%cText%c", ["color:red", ""])
%%Literal %format("%%", [])"%"

%s - String

Converts values to strings.

Behavior:

import { format } from "@visulima/fmt";

console.log(format("%s", [42]));           // "42"
console.log(format("%s", [true]));         // "true"
console.log(format("%s", [[1, 2]]));       // "1,2"
console.log(format("%s", [null]));         // "null"
console.log(format("%s", [undefined]));    // "undefined"
console.log(format("%s", [Symbol("id")])); // "Symbol(id)"

Special Cases:

  • BigInt is not converted to string
  • -0 remains as -0
  • Objects are converted via toString()

%d - Decimal Number

Converts values to numbers.

Behavior:

import { format } from "@visulima/fmt";

console.log(format("%d", [42]));      // "42"
console.log(format("%d", ["123"]));   // "123"
console.log(format("%d", [true]));    // "1"
console.log(format("%d", [false]));   // "0"
console.log(format("%d", ["abc"]));   // "NaN"
console.log(format("%d", [null]));    // "0"

Not Supported:

  • BigInt values
  • Symbol values

%i - Integer

Converts values to integers (truncates decimals).

Behavior:

import { format } from "@visulima/fmt";

console.log(format("%i", [42.7]));    // "42"
console.log(format("%i", [42]));      // "42"
console.log(format("%i", [-42.7]));   // "-42"
console.log(format("%i", ["123.9"])); // "123"

%f - Float

Converts values to floating-point numbers.

Behavior:

import { format } from "@visulima/fmt";

console.log(format("%f", [3.14159])); // "3.14159"
console.log(format("%f", [42]));      // "42"
console.log(format("%f", ["2.5"]));   // "2.5"

Not Supported:

  • Symbol values

%j - JSON

Serializes values as JSON.

Behavior:

import { format } from "@visulima/fmt";

console.log(format("%j", [{ a: 1 }]));        // '{"a":1}'
console.log(format("%j", [[1, 2, 3]]));       // '[1,2,3]'
console.log(format("%j", [null]));            // 'null'
console.log(format("%j", [undefined]));       // undefined (no output)
console.log(format("%j", [() => {}]));        // undefined (no output)

Circular References:

import { format } from "@visulima/fmt";

const obj: any = { name: "test" };
obj.self = obj;

console.log(format("%j", [obj]));
// '{"name":"test","self":"[Circular]"}'

%o and %O - Object

Inspect objects.

%o - Basic Inspection:

import { format } from "@visulima/fmt";

const obj = { a: 1, b: 2 };
console.log(format("%o", [obj]));
// {a: 1, b: 2}

%O - Detailed Inspection:

import { format } from "@visulima/fmt";

const obj = { visible: "yes" };
Object.defineProperty(obj, "hidden", {
  value: "secret",
  enumerable: false
});

console.log(format("%o", [obj]));
// {visible: 'yes'}

console.log(format("%O", [obj]));
// {visible: 'yes', hidden: 'secret'}

%c - CSS Styling

Apply CSS-like styles to terminal output.

Supported Properties:

  • color - Text color
  • background-color - Background color
  • font-weight - bold or normal
  • font-style - italic or normal
  • text-decoration - underline, line-through, or none
  • text-decoration-color - Color for underline/line-through
  • text-decoration-line - Decoration type

Behavior:

import { format } from "@visulima/fmt";

// Red text
format("%cError%c", ["color: red", ""])

// Bold green text
format("%cSuccess%c", ["color: green; font-weight: bold", ""])

// Italic with underline
format("%cNote%c", ["font-style: italic; text-decoration: underline", ""])

// Yellow background
format("%cWarning%c", ["background-color: yellow", ""])

Reset Styles:

import { format } from "@visulima/fmt";

// Empty string resets all styles
format("%cStyled%c Normal", ["color: red", ""])

Note: %c only works in terminals with ANSI color support. In non-color environments, it's ignored.


%% - Literal Percent

Output a literal % character.

Behavior:

import { format } from "@visulima/fmt";

console.log(format("Progress: 50%%", []));  // "Progress: 50%"
console.log(format("%%off", []));           // "%off"

Custom Formatters

Creating Custom Formatters

Add your own format specifiers:

import { build } from "@visulima/fmt";

const format = build({
  formatters: {
    // Single character key
    t: (value) => new Date(value).toLocaleString(),
    u: (value) => new URL(value).hostname,
    h: (value) => `0x${value.toString(16)}`,
    p: (value) => `${(value * 100).toFixed(2)}%`,
    b: (value) => value ? "Yes" : "No"
  }
});

// Use them
console.log(format("Time: %t", [Date.now()]));
console.log(format("Host: %u", ["https://example.com"]));
console.log(format("Hex: %h", [255]));
console.log(format("Percent: %p", [0.75]));
console.log(format("Boolean: %b", [true]));

Formatter Function Signature

type FormatterFunction = (value: any) => string;

Requirements:

  • Must return a string
  • Single parameter (the value to format)
  • Should handle invalid input gracefully

Example:

const safeFormatter = (value: unknown): string => {
  try {
    return String(value);
  } catch {
    return "[Error formatting value]";
  }
};

Custom Stringify

Replace the default JSON serializer:

import { format } from "@visulima/fmt";
import safeStringify from "fast-safe-stringify";

const options = {
  stringify: safeStringify
};

const data = { /* complex object */ };
const result = format("Data: %j", [data], options);

Performance Tips

  1. Reuse built formatters: Call build() once and reuse the returned function
  2. Avoid %O when %o suffices: %O is slower due to non-enumerable property inspection
  3. Use typed parameters: TypeScript helps catch formatting errors at compile time

Next Steps

Usage Guide

Learn how to use all features with examples

Back to Overview

Return to package overview

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