Home > Enterprise >  Node Cluster - replace worker.js file with code
Node Cluster - replace worker.js file with code

Time:11-01

The below example is from Node Documentation :

import cluster from 'cluster';

cluster.setupPrimary({
  exec: 'worker.js',
  args: ['--use', 'https'],
  silent: true
});
cluster.fork(); // https worker
cluster.setupPrimary({
  exec: 'worker.js',
  args: ['--use', 'http']
});
cluster.fork(); // http worker

When packaging the application into a redistributable binary, exec: 'worker.js' is problematic the worker.js has to be packaged along with the exe. Is there a way to tell cluster to look at a piece of code instead?

CodePudding user response:

Yes, of course. That's the usual behavior of cluster when not using the new .setupPrimary method. You can use the env argument of .fork() to pass arguments:

import cluster from 'cluster';

if (cluster.isPrimary) {
  cluster.fork({use: 'https'});
  cluster.fork({use: 'http'});
} else {
  if (process.env.use && process.env.use == 'https') {
    // code for https worker
  } else if (process.env.use && process.env.use == 'http') {
    // code for http worker
  } else {
    console.log("missing 'use' environment variable in worker");
  }
}
  • Related