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

2019-03-09 10:24发布

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.

6条回答
走好不送
2楼-- · 2019-03-09 10:48

Another option is to use node-red-contrib-os package

查看更多
在下西门庆
3楼-- · 2019-03-09 10:51

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.

查看更多
劫难
4楼-- · 2019-03-09 10:54

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...

查看更多
姐就是有狂的资本
5楼-- · 2019-03-09 10:58

Use node process.cpuUsage function (introduced in node v6.1.0). It shows time that cpu spent on your node process. Example taken from docs:

const previousUsage = process.cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);

// set 2 sec "non-busy" timeout
setTimeout(function() {
    console.log(process.cpuUsage(previousUsage);
    // { user: 514883, system: 11226 }    ~ 0,5 sec 
}, 2000);
查看更多
Deceive 欺骗
6楼-- · 2019-03-09 11:01

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);
查看更多
地球回转人心会变
7楼-- · 2019-03-09 11:02

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

查看更多
登录 后发表回答