Something went wrong. Try again.
A set of JavaScript filters and components meant to replicate Django's humanize
Something went wrong. Try again.
human-eyes filesizeformat.js
994 B · 38 lines
JavaScript
at main
123456789101112131415161718192021222324252627282930313233343536373839/** * Django-style filesizeformat for JavaScript. * * Formats a number of bytes as a human-readable file size. * Uses 1024-based conversions with traditional unit names (KB, MB, etc.) * matching Django's behavior. * * @param {number} bytes - The file size in bytes * @returns {string} Human-readable file size * * @example * filesizeformat(0) // "0 bytes" * filesizeformat(1) // "1 byte" * filesizeformat(1024) // "1.0 KB" * filesizeformat(123456789) // "117.7 MB" */export function filesizeformat(bytes) { const value = Number(bytes);
if (!Number.isFinite(value) || value < 0) { return "0 bytes"; }
if (value < 1024) { return `${value} ${value === 1 ? "byte" : "bytes"}`; }
const units = ["KB", "MB", "GB", "TB", "PB"]; let size = value; let unitIndex = -1;
while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; }
return `${size.toFixed(1)} ${units[unitIndex]}`;}