Format File Size

Format bytes to a human readable file size with appropriate units.

Code

Utilities
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0, size = bytes;
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
return `${size.toFixed(2)} ${units[i]}`;

Parameters

Size in bytes.

Browser·fetch() may be limited by CORS

More JavaScript Snippets