1

In Node.js, I want to kill a server running on port 1337. process.kill(pid) seems like the way to do that. But how do I get the pid of the server running on port 1337, in Node.js?

I see plenty of examples of how to do this with ps and lsof. Is there a way to pull this off without relying on shell commands in Node.js?

Here is how I would do this by relying on lsof:

Number(child_process.execSync('lsof -i :1337 -t'))
Jackson
  • 7,927
  • 4
  • 42
  • 65

2 Answers2

2

To answer my question, I can determine the pid(s) at a port with the port-pid package: https://www.npmjs.com/package/port-pid

However, to solve my problem, I instead adopted the philosophy that there was a "good reason" the port was in use, and instead opted to kill the child process from where it was spawned by wrapping require('child_process').spawn:

var childProcess = require('child_process');
var spawn = (function () {
  var children = [];
  process.on('exit', function () {
    children.forEach(function (child) {
      child.kill();
    });
  });
  return function () {
    var child = childProcess.spawn.apply(childProcess, arguments);
    children.push(child);
    return child;
  };
}());
spawn('node', ['server/server.js'])
Jackson
  • 7,927
  • 4
  • 42
  • 65
0

If you launched the server as a child from another nodejs process, you can just do child.pid to get the pid of the server process.

Example:

var child = child_process.spawnSync(command[, args][, options]);
console.log(child.pid);
process.kill(child.pid);
pietrovismara
  • 4,944
  • 4
  • 27
  • 42
  • In my case, the process which originally spawned `node` has exited. i.e., I do not have a `child` object representing the server that I want to kill. – Jackson Mar 27 '16 at 17:05
  • I understand, in this case i don't think you can do without shell commands. You could try with ps-node as also stated [here](http://stackoverflow.com/questions/13206724/how-to-get-the-list-of-process) in the second answer. But i suggest you to refactor your code a bit to avoid this case, or to use some tool as programmatic pm2. – pietrovismara Mar 27 '16 at 17:08