Вопрос

So I run several chatbots via child.fork(../bots/config1.js) and so on. I want to make a web interface for said chat bots to display some data. Since they're child processes, they can't access the same port. Right now I'm doing redirects when I start the bot. For example, in my start file, it looks something like this:

var child = require('child_process');
var express = require('express');
var web = express();
var basehref = 'http://bot.example.com';

var configs = {
  'bot1':{ port:3001,file:'bot1.js',route:'bot1' },
  'bot2':{ port:3001,file:'bot2.js',route:'bot2' }
}

for (var bot in config) {
   var cfg = config[bot];

   child.fork('bots/'+cfg.file);

   web.get('/'+cfg.route,function(req,res){
     res.redirect(basehref+':'+cfg.port+'/'+cfg.route);
   });
}

And I have the bots start their own express server on cfg.port to handle that request. But it feels tacky.

This is the route in the bot file:

web.get('/'+cfg.route,function(req,res){
  var data = { cfg:cfg,local:local,users:users,modules:{} };
  for (var i=0;i < loadedModules.length;i++){
    var module = loadedModules[i];
    data.modules[module.type] = { 
      settings:module.settings,
      toggles:moduletoggles 
    }
  }
  res.render('views/routeIndex',data);
});

So I was wondering if there was any way I could send the data to the child process, and then return the data to the wrapper and make the page there, keeping all the bots on the same port.

I've already tried using cluster, but the routes are complex in the bot file, and therefor can't be defined before the bot is fully operational, and I spent several hours trying before giving up.

Это было полезно?

Решение

Example:

File bot1.js

// this bot echo the message it received
process.on('message', function (message) {
    process.send('Bot says:' + message.toUpperCase());
})

File app.js

var child = require('child_process'), express = require('express');
var app = express();
var bot1 = child.fork('bot1.js');

app.get('/bot1/:message', function (req, res) {
    bot1.send(req.param('message'));
    bot1.once('message', function (reply) {
        res.end(reply);
    })
})

app.listen(3000);

Run:

npm install express
node app.js

On browsers or curl:

http://domain:3000/bot1/hello%20how%20are%20you

Bot says:HELLO HOW ARE YOU
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top