UNPKG

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