Wildlink's Technology Blog

An occasionally updated list of informative articles.
Pulled from our internal wiki.

Typescript - Human Readable File Sizes

Article Information

Article Content

This is a stupid simple function that we discovered some short time ago and now gets copied anytime we need to work with files. Hate that we used to jump through hoops to do this with messy if's.

// #region formatBytes
/**
 * Get bytes in human readable format
 * @param bytes bytes to format
 * @returns Formatted bytes string
 */
public formatBytes(bytes: number): string {
  if (bytes <= 0) return "0 B";
  const sizes = ["B", "KB", "MB", "GB"];
  const lScale = Math.floor(Math.log(bytes) / Math.log(1024));
  const result = bytes / Math.pow(1024, lScale);
  if (result < 10) {
    return `${result.toFixed(1)} ${sizes[lScale]}`;
  }
  return `${result.toFixed(0)} ${sizes[lScale]}`;
}
// #endregion formatBytes