bytes-iec: Byte Unit Conversion Utility

3.1.1 · active · verified Sun Apr 19

bytes-iec is a JavaScript and TypeScript utility library, currently at version 3.1.1, designed for parsing and formatting byte size strings. It converts human-readable strings like '1kB' or '2KiB' into their numeric byte equivalents (e.g., 1000, 2048) and vice-versa. As a fork of the popular `bytes` module, `bytes-iec` differentiates itself by offering comprehensive support for ISO/IEC 80000-13:2008 binary and decimal prefixes, including KiB, MiB, etc., and also includes a JEDEC compatibility mode for legacy definitions where metric units have binary values. A key feature is its default use of decimal metric units, which can be configured globally or per-call. The library is actively maintained, indicated by its recent version and clear feature set, and ships with TypeScript definitions, making it suitable for modern JavaScript and TypeScript projects in Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates formatting byte values into human-readable strings and parsing strings back into numeric bytes, showcasing default decimal mode, explicit binary (IEC) mode, and JEDEC compatibility mode.

import bytes from 'bytes-iec';

// Format bytes to a human-readable string (defaults to decimal metric)
const formattedDecimal = bytes.format(1000000); // 1 MB
console.log(`1,000,000 bytes (decimal): ${formattedDecimal}`);

// Format bytes using binary (IEC) units
const formattedBinary = bytes.format(1048576, { mode: 'binary' }); // 1 MiB
console.log(`1,048,576 bytes (binary): ${formattedBinary}`);

// Parse a human-readable string to bytes (defaults to metric parsing)
const parsedGB = bytes.parse('1GB'); // 1,000,000,000
console.log(`Parsed '1GB' (decimal): ${parsedGB} bytes`);

// Parse a string using binary (IEC) units
const parsedGiB = bytes.parse('1GiB', { mode: 'binary' }); // 1,073,741,824
console.log(`Parsed '1GiB' (binary): ${parsedGiB} bytes`);

// Example with JEDEC (compatibility) mode - where kB, MB are binary
const formattedJedec = bytes.format(1024 * 1024, { mode: 'jedec' }); // 1 MB (binary value)
console.log(`1,048,576 bytes (JEDEC): ${formattedJedec}`);

// Handle null/invalid inputs
const invalidParse = bytes.parse('not-a-byte-string');
console.log(`Parsing 'not-a-byte-string': ${invalidParse}`);

view raw JSON →