Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out the % CPU usage for Node.js process?

Is there a way to find out the cpu usage in % for a node.js process via code. So that when the node.js application is running on the server and detects the CPU exceeds certain %, then it will put an alert or console output.

like image 593
murvinlai Avatar asked Oct 14 '11 21:10

murvinlai


People also ask

How do I check CPU usage in node JS?

The process. cpuUsage() method is an inbuilt application programming interface of the Process module which is used to get the user, system CPU time usage of the current process. It is returned as an object with property user and system, values are in microseconds.

Does NodeJS use CPU?

NodeJS uses Javascript to develop server side applications and shares the same behavior. It runs on one CPU core regardless of how many CPU cores you have in your machine or a virtual machine in the cloud.


2 Answers

On *nix systems can get process stats by reading the /proc/[pid]/stat virtual file.

For example this will check the CPU usage every ten seconds, and print to the console if it's over 20%. It works by checking the number of cpu ticks used by the process and comparing the value to a second measurement made one second later. The difference is the number of ticks used by the process during that second. On POSIX systems, there are 10000 ticks per second (per processor), so dividing by 10000 gives us a percentage.

var fs = require('fs');

var getUsage = function(cb){
    fs.readFile("/proc/" + process.pid + "/stat", function(err, data){
        var elems = data.toString().split(' ');
        var utime = parseInt(elems[13]);
        var stime = parseInt(elems[14]);

        cb(utime + stime);
    });
}

setInterval(function(){
    getUsage(function(startTime){
        setTimeout(function(){
            getUsage(function(endTime){
                var delta = endTime - startTime;
                var percentage = 100 * (delta / 10000);

                if (percentage > 20){
                    console.log("CPU Usage Over 20%!");
                }
            });
        }, 1000);
    });
}, 10000);
like image 112
Zack Bloom Avatar answered Oct 25 '22 18:10

Zack Bloom


Try looking at this code: https://github.com/last/healthjs

Network service for getting CPU of remote system and receiving CPU usage alerts...

Health.js serves 2 primary modes: "streaming mode" and "event mode". Streaming mode allows a client to connect and receive streaming CPU usage data. Event mode enables Health.js to notify a remote server when CPU usage hits a certain threshold. Both modes can be run simultaneously...

like image 30
CrazyDart Avatar answered Oct 25 '22 16:10

CrazyDart