Pages

Tuesday, August 22, 2017

psnode nodejs process lookup

psnode nodejs process lookup

In NodeJs there are various modules available. psnode is a module which will enable to lookup / filter / kill processes.

URL of the psnode project:

https://www.npmjs.com/package/ps-node

To Kill a process based on processID, see the code sample below.

var ps = require('ps-node');
// A simple pid lookup 
ps.kill( '12345', function( err ) {
    if (err) {   
     throw new Error( err );
   }
    else { 
       console.log( 'Process %s has been killed!', pid );   }
});
Lookup process with specified pid:

var ps = require('ps-node');
// A simple pid lookup 
ps.lookup({ pid: 12345 }, function(err, resultList ) {
    if (err) {
        throw new Error( err );
    }  var process = resultList[ 0 ]; if( process ){
        console.log( 'PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments );
    }
    else {
        console.log( 'No such process found!' );
    }
}); 
 
Lookup process with Regular expression and various arguments:

Here we are finding processes based on the

command : ( like node or java or gcc ) ,

ppid  : parent PID. if the PPID is one, then its an orphan process, else the PPID points to the PID of the parent.  Here we are filtering only orphan process. Hence the REGEX "^1$"  [ Starts and ends With one ].

arguments :  Run time arguments like path to the file. etc

resultList comprises of list of processes matching the condition.

var pathTo = "/opt/sample/node.js";
var PIDList=[]
    psnode.lookup({command: 'node', ppid: "^1$", arguments: pathTo}, function(err, resultList ) {
        if (err) {
            throw new Error( err );
        }

        for (var i = 0; i < resultList.length; i){
            var process = resultList[i];
            PIDList.push( process.pid );
        }
    });



No comments:

Post a Comment