On this page
@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
什么是格式化? Jump to heading
格式化是将数据转换为特定布局或样式以供展示的过程。它可以包括添加颜色、调整间距,或者将值转换为人类可读的形式。
何时使用 @std/fmt Jump to heading
如果你需要以用户友好的方式展示数据,尤其是在命令行应用中。
示例 Jump to heading
// 字节数:十进制(kB)与二进制(KiB),带符号值与本地化
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" }); // 例如 "12,35 MB"
// 持续时间:紧凑显示,可选零值忽略
import { format as formatDuration } from "@std/fmt/duration";
formatDuration(90_000); // 例如 "1m 30s"(具体样式可能有所不同)
formatDuration(3_600_000, { ignoreZero: true }); // 例如 "1h"
// printf/sprintf:Go 风格格式化
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");
// 注意:某些说明符如 %v/%i/%I 仅限于 Deno。
// 颜色:组合样式;切换及移除 ANSI 代码
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);
// 写入日志时移除 ANSI 码
const plain = stripAnsiCode(ok);
小贴士 Jump to heading
- 使用 bytes 选项(
binary、bits、locale、minimumFractionDigits、maximumFractionDigits、signed)以符合你的用户体验需求。 - 命令行界面优先简洁的持续时间输出;用
ignoreZero抑制零值。 - 为了可访问性谨慎使用颜色;写入文件或不支持的系统时移除 ANSI 码。
- 需要精确宽度、填充或数字进制时,选择 printf/sprintf。