Search code examples
javascriptnode.jsdiscord.jscpu-usageram

CPU usage as a percentage for the whole system?


I'm trying to make a botinfo command with resource usage stats. I've got memory covered (although percentage for memory usage would be nice too) but I can't seem to get cpu usage. I've tried multiple packages and methods, none worked. My memory thing is:

const usedMemory = os.totalmem() - os.freemem()

How would I make cpu usage and return it in an discord.js embed?


Solution

  • I found a way to do it. There's a function in node-os-utils (https://www.npmjs.com/package/node-os-utils) called loadavgTime that needs to be used with loadavg-windows (https://www.npmjs.com/package/loadavg-windows) if you're on windows. It takes the os.loadavg from the last minute by default. I then divided it by 2 and then multiplied by 10 cos for some reason it outputs a weird number (between 1.__ and 2.__). It gives it as a percentage, you just need to add the % after it when console.log ing it. Here's the code:

    const osu = require('node-os-utils')
    require('loadavg-windows')
    
    const cpu = osu.cpu
    const usage = (cpu.loadavgTime() / 2) * 10
    
    console.log(usage)