【问题标题】:How do you make multiple node.js command line processes talk to each other?如何让多个 node.js 命令行进程相互通信?
【发布时间】:2012-02-20 02:59:22
【问题描述】:

我在搞乱https://github.com/nodejitsu/forever,我想知道您是否以及如何从一个命令行进程向另一个进程发送消息。

在网络上,您使用 HTTP 来回发送请求。但我以前从来没有用命令行做那种事情。我知道这可能与端口和套接字有关,但不太确定从哪里开始……

这是基本设置:

您有一个mainProcess.jschildProcess.js,它们是独立于命令行调用的。不知何故,mainProcess.js 必须在 childProcess.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!")

一种方法是解析日志文件,但这似乎很快就会变得一团糟。似乎有一些协议可以让我将直接消息从一个进程发送到另一个进程,就像使用 HTTP 到 url 一样。你将如何做到这一点?

【问题讨论】:

    标签: node.js command-line tcp protocols


    【解决方案1】:

    在 node.js 中执行 IPC 可以通过多种方式完成。内置,有child_process.fork() API:http://nodejs.org/docs/latest/api/child_processes.html#child_process.fork

    forever 中,有一个选项.fork 将永远使用child_process.fork() API 而不是child_process.spawn()

    var child = forever.start('script-using-fork-api.js', {
      max: 1,
      fork: true,
      silent: true
    });
    

    如果您正在寻找通过网络结帐的 IPC 机制:

    【讨论】:

    猜你喜欢
    • 2011-10-12
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多