问题是:
假设我们有两个 Node.js 进程正在运行:
example1.js
和example2.js
.在
example1.js
有功能func1(input)
返回result1
结果。有没有办法从
example2.js
调用func1(input)
并获得result1
结果呢?
根据我对 Node.js 的了解,我只找到了一种使用套接字进行通信的解决方案。然而,这不太理想,因为它需要一个进程监听端口。如果可能的话,我希望避免这种情况。
编辑:在一些问题之后,我想在层次结构中添加它 example1.js
不能是 example2.js
的子进程,而是相反。此外,如果它有帮助 - 只能有一个 example1.js
处理自己的数据和许多 example2.js
的处理自己的数据+来自第一个进程的数据。
最佳答案
你描述的用例让我想到了dnode ,您可以通过它轻松地公开要由不同进程调用的函数,由 dnode 协调,它使用网络套接字(和 socket.io,因此您可以在浏览器中使用相同的机制)。
另一种方法是使用消息队列,有 many good bindings for different message queues .
据我所知,最简单的方法是使用 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 withchild.send(message, [sendHandle])
and messages are received by a'message'
event on the child.
因此,对于您的示例,您可以使用 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:
function func(input) {
process.send('Hello ' + input);
}
process.on('message', function(m) {
func(m);
});
关于node.js - 在 Node.js 中的两个不同进程之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10213501/