问题描述
假设我们有两个 Node.js 进程在运行:
example1.js
和example2.js
.
在 example1.js
中有函数 func1(input)
返回 result1
作为结果.
In example1.js
there is function func1(input)
which returns result1
as a result.
有没有办法从 example2.js
内部调用 func1(input)
并获得 result1
作为结果?
Is there a way from within example2.js
to call func1(input)
and obtain result1
as the outcome?
根据我对 Node.js 的了解,我只找到了一种使用套接字进行通信的解决方案.然而,这并不理想,因为它需要一个进程侦听端口.如果可能,我希望避免这种情况.
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.
在一些问题之后,我想在层次结构中添加example1.js
不能是example2.js
的子进程,而是相反.此外,如果有帮助 - 只能有一个 example1.js
处理自己的数据,而许多 example2.js
处理自己的数据 + 来自第一个进程的数据.>
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.
推荐答案
你描述的用例让我想起了dnode,使用它,您可以轻松公开由不同进程调用的函数,由 dnode 协调,它使用网络套接字(和 socket.io,因此您可以在浏览器中使用相同的机制).
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.
据我所知,最简单的方法是使用 child_process.fork():
The simplest way to my knowledge, is to use child_process.fork():
这是用于生成 Node 进程的 spawn()
功能的一个特例.除了在普通 ChildProcess 实例中包含所有方法之外,返回的对象还具有内置的通信通道.通道是用 child.send(message, [sendHandle])
写入的,并且消息由子节点上的 'message'
事件接收.
因此,对于您的示例,您可以使用 example2.js:
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'});
还有example1.js:
And example1.js:
function func(input) {
process.send('Hello ' + input);
}
process.on('message', function(m) {
func(m);
});
这篇关于Node.js 中两个不同进程之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!