Package Exports
- bytes-kit
Readme
bytes-kit
A lightweight, type-safe, and zero-dependency utility for formatting byte sizes into human-readable strings (supporting both decimal base-1000 and binary base-1024 units).
Features
- 🚀 Zero dependencies & lightweight
- 📦 Dual package (CommonJS & ES Modules)
- 🔒 Fully type-safe with TypeScript types included
- ⚙️ Highly customizable (decimal places, binary vs. decimal units, spacing, custom forced units)
- 🌍 Localization support using
Intl.NumberFormat
Installation
npm install bytes-kitUsage
Basic Formatting
By default, format uses decimal base-1000 units (e.g., KB, MB, GB):
import { format } from 'bytes-kit';
format(1000); // => '1 KB'
format(1337); // => '1.34 KB'
format(1500000); // => '1.5 MB'
format(-1000); // => '-1 KB' (handles negative values)Binary Units (Base-1024)
Use the binary option to use IEC binary units (e.g., KiB, MiB, GiB):
format(1024, { binary: true }); // => '1 KiB'
format(1.5 * 1024 * 1024, { binary: true }); // => '1.5 MiB'Formatting Options
// Customize decimal places (defaults to 2)
format(1337, { decimalPlaces: 1 }); // => '1.3 KB'
// Force fixed decimal representation (keep trailing zeros)
format(1000, { decimalPlaces: 2, fixedDecimals: true }); // => '1.00 KB'
// Omit the space between value and unit symbol
format(1000, { space: false }); // => '1KB'
// Force formatting to a specific unit
format(1000, { unit: 'B' }); // => '1000 B'
format(1e6, { unit: 'KB' }); // => '1000 KB'Localization (Intl support)
Format numbers according to specific locale representation:
// Localize using German number formatting rules
format(1234567, { locale: 'de-DE' }); // => '1,23 MB'API Reference
format(bytes: number, options?: FormatOptions): string
FormatOptions
| Option | Type | Default | Description |
|---|---|---|---|
binary |
boolean |
false |
If true, uses binary units (base-1024, e.g. KiB, MiB). If false, uses decimal units (base-1000, e.g. KB, MB). |
decimalPlaces |
number |
2 |
The maximum number of decimal places to include. |
fixedDecimals |
boolean |
false |
If true, always displays trailing zeros in the decimal part. |
space |
boolean |
true |
If true, includes a space between the value and the unit. |
unit |
UnitType |
undefined |
Forces conversion to a specific unit (e.g., 'MB', 'GiB'). |
locale |
string | boolean |
false |
Localizes the formatted number string using Intl.NumberFormat. |
License
MIT © Your Name