Search code examples
node.jsprocess

Nodejs discover other instances of Nodejs


A Nodejs process can easily spawn and communicate with child nodejs processes during its runtime. But is there any way for a Nodejs process to become aware of and communicate with other, non-child Nodejs processes, that were spawned by some other source?

I would imagine a solution for detecting other instances could involve running the ps command and filtering the results:

let proc = require('child_process').spawn('ps', [], {
  cwd: __dirname,
  env: process.env
});

(async () => {
  let chunks = [];
  proc.on('data', chunk => chunks.push(chunk.toString('utf8')));
  await new Promise(r => proc.on('exit', r));
  let results = chunks.join('');

  // TODO: Now process the String `results`, searching for lines
  // which seem to describe a Nodejs process. Capture the pids of
  // these lines
})();

Communicating with the pids discovered in this way would likely be a whole other process.

Can this problem be solved? Is there an existing library that does this? Can this be done in a cross-platform way?


Solution

  • There is no generic, detectable signature that is common to all node.js apps by default. So, without programming these node.js apps to be recognizable to other processes on the system, there is no generic way to find all of them other than the process inspection that you mentioned.

    That said, if these are your node.js apps, you certainly could give each one of your node.js apps some scheme for detecting them. There could be all sorts of schemes for this. There are an existing set of service discovery protocols (some of which are listed here) and you could have each of your apps participate in one of these services so the others could discover each other.

    Or, you could make your own central service running on a known port that each of your node.js apps would register a control port with and some identifying characteristics of the app. Any other app could see all the running apps by querying the central service app on a known port. They could then get the control port for any of the other apps and communicate with them over that control port (perhaps using http requests).

    Or, when each app starts, it could drop a text file in a known directory location indicating it's control port and app description. Then, any other of your node.js apps could query the files in that known location and look at the info for each one.