@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
87 lines (86 loc) • 2.59 kB
JavaScript
import os from 'node:os';
import { _mb } from '@naturalcycles/js-lib';
export function memoryUsage() {
const { rss, external, heapUsed, heapTotal } = process.memoryUsage();
return {
rss: _mb(rss),
heapTotal: _mb(heapTotal),
heapUsed: _mb(heapUsed),
external: _mb(external),
};
}
export function memoryUsageFull() {
const { rss, external, heapUsed, heapTotal } = process.memoryUsage();
const totalMem = os.totalmem();
const freeMem = os.freemem();
return {
rss: _mb(rss),
heapTotal: _mb(heapTotal),
heapUsed: _mb(heapUsed),
external: _mb(external),
totalMem: _mb(totalMem),
freeMem: _mb(freeMem),
usedMem: _mb(totalMem - freeMem),
};
}
class ProcessUtil {
timer;
startMemoryTimer(intervalMillis = 1000) {
console.log(memoryUsage());
this.timer = setInterval(() => {
console.log(memoryUsage());
}, intervalMillis);
}
stopMemoryTimer(afterMillis = 0) {
setTimeout(() => clearInterval(this.timer), afterMillis);
}
cpuAvg() {
const avg = os.loadavg();
return {
avg1: avg[0].toFixed(2),
avg5: avg[1].toFixed(2),
avg15: avg[2].toFixed(2),
};
}
cpuInfo() {
const cpus = os.cpus();
const c = cpus[0];
return {
count: cpus.length,
model: c?.model || '',
speed: c?.speed || 0,
};
}
async cpuPercent(ms) {
const stats1 = this.getCPUInfo();
const startIdle = stats1.idle;
const startTotal = stats1.total;
return await new Promise(resolve => {
setTimeout(() => {
const stats2 = this.getCPUInfo();
const endIdle = stats2.idle;
const endTotal = stats2.total;
const idle = endIdle - startIdle;
const total = endTotal - startTotal;
if (!total) {
resolve(0);
return;
}
const perc = idle / total;
resolve(Math.round((1 - perc) * 100));
}, ms);
});
}
getCPUInfo() {
// oxlint-disable-next-line unicorn/no-array-reduce
return os.cpus().reduce((r, cpu) => {
r.idle += cpu.times.idle;
Object.values(cpu.times).forEach(m => (r.total += m));
return r;
}, {
idle: 0,
total: 0,
});
}
}
export const processSharedUtil = new ProcessUtil();