🚀 Building a CPU & Memory Monitor in Node.js
node:os module imports the CPU info, memory info , uptime, system-level stats they all are coming from the os module.
we design a function named monitor which calculate the CPU and Memory usage.
oldCpus=os.cpus(); : This is calculating the cpus info like idle time, user time, system time etc.
we call a method setTimeout() : This will call repeatly os.cpus() method for the comparison purpose . Like idle=newCpus-oldCpus
const newCpus=os.cpus(); : This calculate the new cpus stats.
const usage = newCpus.map((cpu, idx) => {
return {
core: idx,
usage: calculateCPU(oldCpus[idx], newCpus[idx]) + "%",
};
});
This is calculating the usage for CPU Core where loop will execute for every core with the help of map() method and calculate the
usage percentage = calculateCPU(oldCpus[idx], newCpus[idx])
output like:
[
{ core: 0, usage: "10.5%" },
{ core: 1, usage: "7.8%" }
]
print the table form these array
console.clear();
console.table(usage);
like this┌─────────┬──────┬─────────┐
│ (index) │ core │ usage │
├─────────┼──────┼─────────┤
│ 0 │ 0 │ '12.3%' │
│ 1 │ 1 │ '8.7%' │
└─────────┴──────┴─────────┘
This line
const usedMemory = (os.totalmem() - os.freemem()) / (1024 * 1024 * 1024);
This line calculate the total memory and free memory and usages memory
import os from "node:os";
function monitor() {
const oldCpus = os.cpus();
setTimeout(() => {
const newCpus = os.cpus();
const usage = newCpus.map((cpu, idx) => {
return {
core: idx,
usage: calculateCPU(oldCpus[idx], newCpus[idx]) + "%",
};
});
console.clear();
console.table(usage);
const usedMemory = (os.totalmem() - os.freemem()) / (1024 * 1024 * 1024);
console.log(
`Memory Used: ${usedMemory.toFixed(2)} GB/${(
os.totalmem() /
(1024 * 1024 * 1024)
).toFixed(2)} GB`
);
}, 1000);
}
function calculateCPU(oldCpus, newCpus) {
const oldTotal = Object.values(oldCpus.times).reduce((a, b) => a + b);
const newTotal = Object.values(newCpus.times).reduce((a, b) => a + b);
const idle = newCpus.times.idle - oldCpus.times.idle;
const total = newTotal - oldTotal;
const used = total - idle;
return ((100 * used) / total).toFixed(1);
}
setInterval(monitor, 1000);
Comments
Post a Comment