Deno nuggets: Print size in readable form

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to print any size in human readable form?

1000 -> 1 KB
98663387987987879 -> 98.7 PB

Solution

Deno’s standard library comes with a fmt module that contains a bytes module, which can be used to print any kind of size into a human-readable form. This module was originally called pretty bytes.

First, we need to import the prettyBytes API from the module:

import { prettyBytes } from "https://deno.land/std/fmt/bytes.ts";

In the simplest form, the prettyBytes API takes a number as input and returns a string:

export function prettyBytes(
num: number,
options: PrettyBytesOptions = {},
): string

Here are some examples of using this API:

import { prettyBytes as pb } from "https://deno.land/std/fmt/bytes.ts";console.log(pb(1));
console.log(pb(10));
console.log(pb(100));
console.log(pb(1000));
console.log(pb(10000));
console.log(pb(100000));
console.log(pb(1000000));
console.log(pb(10000000));
console.log(pb(100000000));
console.log(pb(1000000000));
console.log(pb(10000000000));
console.log(pb(100000000000));

Here is the output of a quick run:

> deno run app.ts 
1 B
10 B
100 B
1 kB
10 kB
100 kB
1 MB
10 MB
100 MB
1 GB
10 GB
100 GB

--

--