How do you make multiple node.js command line processes talk to each other?

Problem

I am messing around with https://github.com/nodejitsu/forever, and am wondering in general if and how you send messages from one command line process to another.

On the web, you use HTTP to send requests back and forth. But I've never had to do that type of thing with the command line before. I know it probably has to do with ports and sockets, but not so sure where to start…

Here's the basic setup:

You have a mainProcess.js and childProcess.js, and they are invoked independently from the command line. Somehow, mainProcess.js must run a callback whenever childProcess.js sends it a message.

./parent.js:

var forever       = require("forever");
var mainProcess   = forever.start(["node", "mainProcess.js"], {max: 1, silent: true});
mainProcess.on("stdout", function(data) {
  console.log(data.toString().trim());
});
mainProcess.on("stderr", function(data) {
  console.log(data.toString().trim());
});
forever.startServer(mainProcess);

./child.js:

var forever       = require("forever");
var childProcess  = forever.start(["node", "childProcess.js"], {max: 1, silent: true});
childProcess.on("stdout", function(data) {
  // *send to parent process*
});
forever.startServer(childProcess);

./childProcess.js

console.log("A Message from a child process!")

One way to do it is to parse log files, but that seems like it'd get messy quick. It seems like there's some protocol out there that will allow me to send direct messages from one process to another the same way you would with HTTP to a url. How would you accomplish this?

Problem courtesy of: Lance Pollard

Solution

Performing IPC in node.js can be accomplished in a number of ways. Built in, there is the child_process.fork() API: http://nodejs.org/docs/latest/api/child_processes.html#child_process.fork

In forever, there is an option, .fork which will tell forever to use the child_process.fork() API instead of child_process.spawn():

var child = forever.start('script-using-fork-api.js', {
  max: 1,
  fork: true,
  silent: true
});

If you're looking for IPC mechanisms which go over the network checkout:

Solution courtesy of: indexzero

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.