get system cpu usage in typescript

To get the system CPU usage in TypeScript, you can use the os module in Node.js. Here's an example code snippet:

index.ts
import os from 'os';

const cpuUsage = os.loadavg()[0] / os.cpus().length;
console.log(`CPU usage: ${cpuUsage.toFixed(2)}%`);
126 chars
5 lines

Explanation:

  • The os.loadavg() method returns an array containing the 1, 5, and 15 minute load averages. We use the first element of this array (which represents the 1 minute load average) to calculate the CPU usage.
  • The os.cpus() method returns an array of objects containing information about each CPU/core of the system. We use the length property of this array to get the total number of CPUs/cores.
  • Finally, we divide the 1 minute load average by the number of CPUs/cores to get the CPU usage percentage. The toFixed(2) method is used to round the result to 2 decimal places.

gistlibby LogSnag