简体   繁体   中英

Can I define Express routes in a child process?

So I run a bunch of a little chatbots written in node, nothing too exciting. However, I recently decided to give them their own little web page to display information in a graphical manner. To do this, I figured I'd just run express.

However, I'm running my bots with a wrapper file that starts each chatbot as a child process. Which makes using express a little tricky. Currently I'm starting the express server in the wrapper.js file like so:

var express = require("express");  
var web = express();  
web.listen(3001);

And then in the child processes, I'm doing this:

var express = require("express");
var web = express();
web.get("/urlforbot",function (req,res) {
   res.send("Working!"); 
});

However, when I navigate to :3001/urlforbot , I get Cannot GET /urlforbot .

Any idea what I'm doing wrong and how to fix this?

Edit : This is my complete wrapper file: http://snippi.com/s/3vn56m2

Edit 2 : This is what I'm doing now. I'm hosting each bot on it's own port, and storing that information in the configs. This is the code I'm using, and it appears to be working:

web.get("/"+cfg.route, function (req,res) { // forward the data
   res.redirect('http://url.com:'+cfg.port+"/"+cfg.route);
});

Since your bots run as separate processes (any particular reason?), you have to treat each one as having to implement their own HTTP server with Express:

var express = require("express");
var web = express();
web.get("/urlforbot",function (req,res) {
   res.send("Working!"); 
});
web.listen(UNIQUE_PORT_NUMBER);

Each bot process needs to listen on a unique port number, it can't be shared.

Next, you need to map requests coming in on port 3001 in the 'master' process to the correct child process' Express server.

node-http-proxy has a useful option called a ProxyTable with which to create such a mapping, but it requires the master process to know what the endpoint ( /urlforbot in your terms) for each bot is. It also requires that the master knows on which port the bots are listening.

EDIT: alternatively, you can use child_process.fork to fork a new process for each of your bots, and communicate between them and the master process (port numbers and such, or even all the data required to generate the /urlforbot pages) using the comm channel that Node provides, but that still sounds like an overly complex setup.

Wouldn't it be possible to create a Bot class instead? You'd instantiate the class for each bot you want to run, and that instance loads its specific configuration and adds its routes to the Express server. All from the same process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM