Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass variables to cluster.fork in node.js?

Tags:

node.js

So right now I have a bunch of chat bots, and I use a wrapper to start each one as a child process. It forks a config file. However, since each bot has a webiste, it means that express has to run on an unique port for each bot. I would like to have all the bots run the webserver on the same port. Which led me to look at cluster rather than child.

I am currently using child.fork(config.js); to spawn the bots, and it's working as well as can be expected.

But Is there any way to pass the config variables to cluster.fork so each worker can connect to its own chat room with its own login credentials?

And if it is possible, is there a way to kill/restart a worker like a child process?

like image 723
Dalton Gore Avatar asked Nov 17 '25 22:11

Dalton Gore


1 Answers

Check out the documentation

You could augment your process.env, and then use that in the forked process.

var _ = require('lodash');
var child = require('child_process');
var env = _.clone(process.env);

env.BOT_ID = 'dalton';
child.fork('./config.js', { env: env });

I'd suggest you keep the smallest amount of info in env, and then just use that to grab the configuration from a JSON file, or something.

like image 54
bevacqua Avatar answered Nov 19 '25 12:11

bevacqua