(
bytes: number,
options?: { includeBytes?: boolean; precision?: number }
)
| 455 | * @returns Formatted string (e.g., "1.5 MB", "500 KB") |
| 456 | */ |
| 457 | export function formatFileSize( |
| 458 | bytes: number, |
| 459 | options?: { includeBytes?: boolean; precision?: number } |
| 460 | ): string { |
| 461 | if (bytes === 0) return '0 Bytes' |
| 462 | |
| 463 | const k = 1024 |
| 464 | const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'] |
| 465 | const precision = options?.precision ?? 1 |
| 466 | const includeBytes = options?.includeBytes ?? false |
| 467 | |
| 468 | const i = Math.floor(Math.log(bytes) / Math.log(k)) |
| 469 | |
| 470 | if (i === 0 && !includeBytes) { |
| 471 | return '0 Bytes' |
| 472 | } |
| 473 | |
| 474 | const value = bytes / k ** i |
| 475 | const formattedValue = Number.parseFloat(value.toFixed(precision)) |
| 476 | |
| 477 | return `${formattedValue} ${sizes[i]}` |
| 478 | } |
| 479 | |
| 480 | /** |
| 481 | * Validate file size and type for knowledge base uploads (client-side) |
no test coverage detected