我正在摆弄https://github.com/nodejitsu/forever ,并且一般想知道是否以及如何从一个命令行进程向另一个进程发送消息。
在网络上,您使用 HTTP 来回发送请求。但我以前从未需要使用命令行执行此类操作。我知道这可能与端口和套接字有关,但不太确定从哪里开始......
这是基本设置:
您有一个 mainProcess.js
和 childProcess.js
,它们是独立于命令行调用的。不知何故,每当 childProcess.js
向其发送消息时,mainProcess.js
都必须运行回调。
./parent.js
:
var forever = require("forever");
var mainProcess = forever.start(["node", "mainProcess.js"], {max: 1, silent: true});
mainProcess.on("stdout", function(data) {
console.log(data.toString().trim());
});
mainProcess.on("stderr", function(data) {
console.log(data.toString().trim());
});
forever.startServer(mainProcess);
./child.js
:
var forever = require("forever");
var childProcess = forever.start(["node", "childProcess.js"], {max: 1, silent: true});
childProcess.on("stdout", function(data) {
// *send to parent process*
});
forever.startServer(childProcess);
./childProcess.js
console.log("A Message from a child process!")
一种方法是解析日志文件,但这似乎很快就会变得困惑。似乎有某种协议(protocol)允许我将直接消息从一个进程发送到另一个进程,就像使用 HTTP 发送到 url 一样。您将如何实现这一目标?
最佳答案
在 Node.js 中执行 IPC 可以通过多种方式完成。内置有 child_process.fork()
API:http://nodejs.org/docs/latest/api/child_processes.html#child_process.fork
在forever
中,有一个选项.fork
,它将告诉forever使用child_process.fork()
API而不是child_process.spawn()
:
var child = forever.start('script-using-fork-api.js', {
max: 1,
fork: true,
silent: true
});
如果您正在寻找通过网络结帐的 IPC 机制:
关于node.js - 如何让多个 Node.js 命令行进程相互通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9355678/