1

I'm trying to get a value into a variable from the osutils cpu usage method, but seem to be having some troubles in doing so.

const osutils = require('os-utils')

function getCPUUsage () {
  const usage = osutils.cpuUsage((value) => {
    return value
  });

  return usage
}

I need to console.log the getCPUUsage function and expect it to contain a value

Ryan H
  • 2,620
  • 4
  • 37
  • 109

1 Answers1

1

I would suggest using Promises and wrapping the cpuUsage call like so:

const osutils = require('os-utils')

function getCPUUsage () {
    return new Promise(resolve => { 
        osutils.cpuUsage(value => resolve(value))
    })
}

async function testCPUUsage() {
    const cpuUsage = await getCPUUsage();
    console.log(`test CPU usage: ${(cpuUsage * 100).toFixed(1)}%`);
}

testCPUUsage();
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40