简体   繁体   中英

Can I pass variables to cluster.fork in 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?

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.

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