From 6907543fb8bc6de201166897ab06e15668271780 Mon Sep 17 00:00:00 2001 From: cswimr Date: Wed, 12 Feb 2025 08:20:57 -0600 Subject: [PATCH] feat(sync): format byte numbers in download logs --- packages/sync/src/sync.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/sync/src/sync.ts b/packages/sync/src/sync.ts index 6048d1c..223e104 100644 --- a/packages/sync/src/sync.ts +++ b/packages/sync/src/sync.ts @@ -41,7 +41,22 @@ async function downloadFile( doHashesMatch(hash, hashFormat, dataBuffer); console.log(`Saving file to ${path.toString()}`); const fileSize = await write(path.toString(), arrayBuffer); - console.log(`Saved ${fileSize} file to ${path.toString()}`); + console.log(`Saved ${formatBytes(fileSize)} file to ${path.toString()}`); +} + +/** + * Converts bytes into a human-readable format with size units. + * @param bytes - The number of bytes. + * @param decimals - The number of decimal places to use. + * @returns Formatted string (e.g., "1.23 MB"). + */ +function formatBytes(bytes: number, decimals: number = 2) { + if (bytes === 0) return "0 Bytes"; + const k = 1024; // or 1000 for decimal units + const dm = decimals < 0 ? 0 : decimals; + const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i]; } /**