Node does not seem to have a system call to kill a process (given I know its PID), or does it?
If there is no built-in function for this, what is a valid cross-platform approach?
Node does not seem to have a system call to kill a process (given I know its PID), or does it?
If there is no built-in function for this, what is a valid cross-platform approach?
The terminate library has seemingly been built for this purpose. It is cross-platform. (I tried it on Windows and MAC.)
Here is a working sample. It also illustrates how to find PID by PORT.
Example:
const { promisify } = require('util');
/**
* NOTE: as of 2021, terminate is still callback-based.
*/
const terminate = promisify(require('terminate'));
await terminate(myPid);
console.log('Process terminated.');
Note that if the process does not exist (or in case of any other problems), it will throw, so you might want to try/catch correspondingly.
terminatelibrary also usesprocess.killunder the hood, but it also deals with some processes needing more than one kill signal, and makes sure that all children are killed as well.