is there a way to find out the % cpu usage for a node.js process with the code? so that when the node.js server is running and detect the CPU is over certain%, then it will put an alert or console output.

share|improve this question

5 Answers

up vote 4 down vote accepted

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

share|improve this answer
This hasnt been updated in a long time and doesnt seem to work any more. – Garrows Jul 3 '12 at 4:43
4  
You dont mark me down for it... its not my fault! I made that comment a year ago. – CrazyDart Jul 3 '12 at 16:58

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);
share|improve this answer

You can use the os module now.

var os = require('os');
var loads = os.loadavg();

This gives you the load average for the last 60seconds, 5minutes and 15minutes. This doesnt give you the cpu usage as a % though.

share|improve this answer
load average is for the entire system. The question is about getting the stats for the current process. – bluesmoon Jul 31 '12 at 14:54

see node-usage for tracking process CPU and Memory Usage (not the system)

share|improve this answer

If you haven't already, try taking a look at https://nodetime.com

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.