Skip to content

Instantly share code, notes, and snippets.

@Digital39999
Last active August 28, 2024 11:53
Show Gist options
  • Save Digital39999/1acd79c92b0069c9774d08cc8b860794 to your computer and use it in GitHub Desktop.
Save Digital39999/1acd79c92b0069c9774d08cc8b860794 to your computer and use it in GitHub Desktop.
import { exec } from 'node:child_process';
import os from 'node:os';
export function getProcessUsage() {
let command = '';
switch (os.platform()) {
case 'darwin': command = `ps -p ${process.pid} -o %cpu,rss`; break;
case 'linux': command = `ps -p ${process.pid} -o %cpu,rss`; break;
default: return Promise.reject(new Error('Unsupported platform!'));
}
const formatBytes = (bytes: number) => {
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0MB';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + sizes[i];
};
const formatCpu = (cpu: number, numCores?: number) => {
return numCores ? `${(cpu / numCores).toFixed(2)}%` : `${cpu.toFixed(2)}%`;
};
return new Promise<{ cpuUsage: string; memoryUsage: string; coreUsage: string; }>((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) return reject(error);
else if (stderr) return reject(new Error(stderr));
const lines = stdout.trim().split('\n');
if (lines.length < 2) return reject(new Error('Unexpected output!'));
const data = lines[1].trim().split(/\s+/);
const numCores = os.cpus().length;
resolve({
cpuUsage: formatCpu(parseFloat(data[0]), numCores),
coreUsage: formatCpu(parseFloat(data[0])),
memoryUsage: formatBytes(parseInt(data[1]) * 1024),
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment