How to extend ChildProcess prototype?

36 views
Skip to first unread message

Nicholas Sotiros

unread,
Aug 8, 2014, 6:31:39 PM8/8/14
to nod...@googlegroups.com
There is an old thread Opinions on exposing core node constructors, e.g. ChildProcess, dedicated to discussion about exposing the ChildProcess constructor.  Currently I find it by doing `spawn('cmd').constructor` but this seems like a bad hack.  I want a better kill() method that is platform dependent (windows or linux), and also reaps all of child's children.  So my code is as follows,

cp
= require('child_process');

switch (process.platform) {
 
case 'win32':
   
ChildProcess = cp.spawn('cmd').constructor;
   
ChildProcess.prototype.kill = function() {
      cp
.exec("taskkill /F /T /PID " + this.pid, function(error, stdout, stderr) {
       
if(error) console.error(error);
     
});
   
};
    spawn
= function(command, commandline) {
      cp
.spawn('cmd', ['/C', command].concat(commandline));
   
};
   
break;
 
default:
   
ChildProcess = cp.spawn('ls').constructor;
   
ChildProcess.prototype.kill = function() {
      cp
.exec("kill -TERM -" + this.pid, function(error, stdout, stderr) {
       
if(error) console.error(error);
     
});
   
};
    spawn
= function(command, commandline) {
      cp
.spawn(command, commandline, {detached: true});
   
};
}

I don't understand why `require('child_process').ChildProcess` is not available.

Sam Roberts

unread,
Aug 9, 2014, 3:05:02 AM8/9/14
to nod...@googlegroups.com
> ChildProcess.prototype.kill = function() {
> cp.exec("kill -TERM -" + this.pid, function(error, stdout, stderr) {
> if(error) console.error(error);
> });

Why not just write a module, that exposes the kindof kill you want?
Your version isn't even API compatible with the original.

Btw, rather than forking an external command on unix to kill your
process group, try `process.kill(-process.pid, 'SIGTERM')`
Reply all
Reply to author
Forward
0 new messages