UNPKG

1.42 kBJavaScriptView Raw
1import { isProduction } from "./env.js";
2
3const sizes = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB"];
4
5/**
6 * Convert bytes to a human readable value
7 *
8 * @since 0.1.0
9 *
10 * @param {number} [bytes]
11 * @returns {string}
12 */
13export function bytesToHumanReadable(bytes) {
14 if (bytes === 0 || bytes === undefined) {
15 return "0 Byte";
16 }
17
18 const idx = Math.floor(Math.log(bytes) / Math.log(1024));
19 const value = bytes / Math.pow(1024, idx);
20
21 let result = value.toFixed(2);
22
23 // Remove trailing zeroes
24 if (result.endsWith(".00")) {
25 result = result.substring(0, result.length - 3);
26 } else if (result.endsWith("0")) {
27 result = result.substring(0, result.length - 1);
28 }
29 return `${result} ${sizes[idx]}`;
30}
31
32/**
33 * Print memory usage of this Node.js process
34 *
35 * @since 0.1.0
36 *
37 * @param {import("./logger.js").Logger} logger
38 * @returns {void}
39 */
40export function printProcessMemoryUsage(logger) {
41 const { external, heapTotal, heapUsed, rss, arrayBuffers } =
42 process.memoryUsage();
43 if (isProduction()) {
44 logger.info({
45 rss,
46 heapUsed,
47 heapTotal,
48 external,
49 arrayBuffers,
50 });
51 } else {
52 logger.info({
53 rss: bytesToHumanReadable(rss),
54 heapUsed: bytesToHumanReadable(heapUsed),
55 heapTotal: bytesToHumanReadable(heapTotal),
56 external: bytesToHumanReadable(external),
57 arrayBuffers: bytesToHumanReadable(arrayBuffers),
58 });
59 }
60}