Communicating between two different processes in Node.js


Question

The issue is:

  • Lets assume we have two Node.js processes running: example1.js and example2.js.

  • In example1.js there is function func1(input) which returns result1 as a result.

  • Is there a way from within example2.js to call func1(input) and obtain result1 as the outcome?

From what I've learned about Node.js, I have only found one solution which uses sockets for communication. This is less than ideal however because it would require one process listening on a port. If possible I wish to avoid that.


EDIT: After some questions I'd love to add that in hierarchy example1.js cannot be child process of example2.js, but rather the opposite. Also if it helps -- there can be only one example1.js processing its own data and many example2.js's processing own data + data from first process.

1
45
2/17/2016 3:37:00 PM

Accepted Answer

The use case you describe makes me think of dnode, with which you can easily expose functions to be called by different processes, coordinated by dnode, which uses network sockets (and socket.io, so you can use the same mechanism in the browser).

Another approach would be to use a message queue, there are many good bindings for different message queues.

The simplest way to my knowledge, is to use child_process.fork():

This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. The channel is written to with child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.

So, for your example, you could have example2.js:

var fork = require('child_process').fork;
var example1 = fork(__dirname + '/example1.js');

example1.on('message', function(response) {
  console.log(response);
});

example1.send({func: 'input'});

And example1.js:

function func(input) {
  process.send('Hello ' + input);
}

process.on('message', function(m) {
  func(m);
});
46
4/18/2012 4:40:37 PM

Use Redis as a message bus/broker.

https://redis.io/topics/pubsub

You can also use socket messaging like ZeroMQ, which are point to point / peer to peer, instead of using a message broker like Redis.

How does this work?

With Redis, in both your node applications you have two Redis clients doing pub/sub. So each node.js app would have a publisher and subscriber client (yes you need 2 clients per node process for Redis pub/sub)

With ZeroMQ, you can send messages via IPC channels, directly between node.js processes, (no broker involved - except perhaps the OS itself..).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon