node.js - 在 Node.js 中的两个不同进程之间进行通信

标签 node.js process

问题是:

  • 假设我们有两个 Node.js 进程正在运行:example1.jsexample2.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 with child.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/

相关文章:

javascript - Evernote API NoteStore#updateNote 修改笔记更新时间,无论实际更改哪个字段

在 UNIX 中杀死父进程的所有子进程的 C/C++ 程序?

c++ - 防止子进程进行系统调用

c - 过程 Controller 以随机顺序运行文件

c++ - qt 创建 gst-launch 进程

javascript - MongoError : topology was destroyed sailsjs

javascript - 如何分别测试 ExpressJS 路由和 'controller'

node.js - 从 Rust 生成的 Node FFI 调用和动态库

java - Process.waitFor() 一个线程

javascript - Node js 从 tcp 套接字 net.createServer 读取特定消息