@std/fmt
Overview Jump to heading
Provides utilities for formatting text of different types:
import { format } from "@std/fmt/bytes";
import { red } from "@std/fmt/colors";
console.log(red(format(1337))); // Prints "1.34 kB"
Runtime compatibility
bytes,
colors, and
duration supports all major runtimes.
printf is mostly compatible with major
runtimes, however some of features, such as %v
, %i
and %I
format
specifiers, are only available in Deno. See the API docs for details.
Add to your project Jump to heading
deno add jsr:@std/fmt
See all symbols in @std/fmt on
What is formatting? Jump to heading
Formatting is the process of transforming data into a specific layout or style for presentation. This can include adding colors, adjusting spacing, or converting values into human-readable forms.
When to use @std/fmt Jump to heading
If you need to present data in a user-friendly way, especially in command-line applications.
Examples Jump to heading
// Bytes: base‑10 (kB) vs binary (KiB), signed values, and locale
import { format as formatBytes } from "@std/fmt/bytes";
formatBytes(1337); // "1.34 kB"
formatBytes(1536, { binary: true }); // "1.50 KiB"
formatBytes(-4096, { signed: true }); // "-4.10 kB"
formatBytes(12_345_678, { locale: "de-DE" }); // e.g., "12,35 MB"
// Duration: compact display with optional zero suppression
import { format as formatDuration } from "@std/fmt/duration";
formatDuration(90_000); // e.g., "1m 30s" (exact style may vary)
formatDuration(3_600_000, { ignoreZero: true }); // e.g., "1h"
// printf/sprintf: Go‑style formatting
import { printf, sprintf } from "@std/fmt/printf";
printf("%-10s %08d 0x%X\n", "build#", 42, 3735928559);
const line = sprintf("%6.2f%% %s", 12.3456, "complete");
// Note: some specifiers like %v/%i/%I are Deno‑only.
// Colors: compose styles; toggle and strip ANSI codes
import {
bold,
getColorEnabled,
green,
red,
setColorEnabled,
stripAnsiCode,
} from "@std/fmt/colors";
setColorEnabled(true);
const ok = bold(green("OK"));
const err = bold(red("ERROR"));
console.log(ok, err);
// Remove ANSI when writing to logs
const plain = stripAnsiCode(ok);
Tips Jump to heading
- Use bytes options (
binary
,bits
,locale
,minimumFractionDigits
,maximumFractionDigits
,signed
) to match your UX. - Prefer concise duration output for CLIs; suppress zeros with
ignoreZero
. - Be conservative with colors for accessibility; strip ANSI when writing to files or systems that don’t support it.
- Reach for printf/sprintf when you need exact widths, padding, or numeric bases.