Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

process - Communicating between two different processes in Node.js

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...