{ "type": "module", "source": "doc/api/cluster.md", "modules": [ { "textRaw": "Cluster", "name": "cluster", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/cluster.js

\n

A single instance of Node.js runs in a single thread. To take advantage of\nmulti-core systems, the user will sometimes want to launch a cluster of Node.js\nprocesses to handle the load.

\n

The cluster module allows easy creation of child processes that all share\nserver ports.

\n
const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', (worker, code, signal) => {\n    console.log(`worker ${worker.process.pid} died`);\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case it is an HTTP server\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end('hello world\\n');\n  }).listen(8000);\n\n  console.log(`Worker ${process.pid} started`);\n}\n
\n

Running Node.js will now share port 8000 between the workers:

\n
$ node server.js\nMaster 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n
\n

On Windows, it is not yet possible to set up a named pipe server in a worker.

", "miscs": [ { "textRaw": "How it works", "name": "How it works", "type": "misc", "desc": "

The worker processes are spawned using the child_process.fork() method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.

\n

The cluster module supports two methods of distributing incoming\nconnections.

\n

The first one (and the default one on all platforms except Windows),\nis the round-robin approach, where the master process listens on a\nport, accepts new connections and distributes them across the workers\nin a round-robin fashion, with some built-in smarts to avoid\noverloading a worker process.

\n

The second approach is where the master process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.

\n

The second approach should, in theory, give the best performance.\nIn practice however, distribution tends to be very unbalanced due\nto operating system scheduler vagaries. Loads have been observed\nwhere over 70% of all connections ended up in just two processes,\nout of a total of eight.

\n

Because server.listen() hands off most of the work to the master\nprocess, there are three cases where the behavior between a normal\nNode.js process and a cluster worker differs:

\n
    \n
  1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
  2. \n
  3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess.
  4. \n
  5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame \"random\" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. To listen\non a unique port, generate a port number based on the cluster worker ID.
  6. \n
\n

Node.js does not provide routing logic. It is, therefore important to design an\napplication such that it does not rely too heavily on in-memory data objects for\nthings like sessions and login.

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on a program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. If no workers are alive, existing connections\nwill be dropped and new connections will be refused. Node.js does not\nautomatically manage the number of workers, however. It is the application's\nresponsibility to manage the worker pool based on its own needs.

\n

Although a primary use case for the cluster module is networking, it can\nalso be used for other use cases requiring worker processes.

" } ], "classes": [ { "textRaw": "Class: `Worker`", "type": "class", "name": "Worker", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "\n

A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.

", "events": [ { "textRaw": "Event: `'disconnect'`", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "params": [], "desc": "

Similar to the cluster.on('disconnect') event, but specific to this worker.

\n
cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n
" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v0.7.3" ], "changes": [] }, "params": [], "desc": "

This event is the same as the one provided by child_process.fork().

\n

Within a worker, process.on('error') may also be used.

" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "params": [ { "textRaw": "`code` {number} The exit code, if it exited normally.", "name": "code", "type": "number", "desc": "The exit code, if it exited normally." }, { "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.", "name": "signal", "type": "string", "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed." } ], "desc": "

Similar to the cluster.on('exit') event, but specific to this worker.

\n
const worker = cluster.fork();\nworker.on('exit', (code, signal) => {\n  if (signal) {\n    console.log(`worker was killed by signal: ${signal}`);\n  } else if (code !== 0) {\n    console.log(`worker exited with error code: ${code}`);\n  } else {\n    console.log('worker success!');\n  }\n});\n
" }, { "textRaw": "Event: `'listening'`", "type": "event", "name": "listening", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`address` {Object}", "name": "address", "type": "Object" } ], "desc": "

Similar to the cluster.on('listening') event, but specific to this worker.

\n
cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n
\n

It is not emitted in the worker.

" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`handle` {undefined|Object}", "name": "handle", "type": "undefined|Object" } ], "desc": "

Similar to the 'message' event of cluster, but specific to this worker.

\n

Within a worker, process.on('message') may also be used.

\n

See process event: 'message'.

\n

Here is an example using the message system. It keeps a count in the master\nprocess of the number of HTTP requests received by the workers:

\n
const cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  let numReqs = 0;\n  setInterval(() => {\n    console.log(`numReqs = ${numReqs}`);\n  }, 1000);\n\n  // Count requests\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  const numCPUs = require('os').cpus().length;\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  for (const id in cluster.workers) {\n    cluster.workers[id].on('message', messageHandler);\n  }\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server((req, res) => {\n    res.writeHead(200);\n    res.end('hello world\\n');\n\n    // Notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n
" }, { "textRaw": "Event: `'online'`", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [], "desc": "

Similar to the cluster.on('online') event, but specific to this worker.

\n
cluster.fork().on('online', () => {\n  // Worker is online\n});\n
\n

It is not emitted in the worker.

" } ], "methods": [ { "textRaw": "`worker.disconnect()`", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v7.3.0", "pr-url": "https://github.com/nodejs/node/pull/10019", "description": "This method now returns a reference to `worker`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {cluster.Worker} A reference to `worker`.", "name": "return", "type": "cluster.Worker", "desc": "A reference to `worker`." }, "params": [] } ], "desc": "

In a worker, this function will close all servers, wait for the 'close' event\non those servers, and then disconnect the IPC channel.

\n

In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.

\n

Causes .exitedAfterDisconnect to be set.

\n

After a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker will close allowing it\nto die gracefully.

\n

The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.

\n

In a worker, process.disconnect exists, but it is not this function;\nit is disconnect().

\n

Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe 'disconnect' event has not been emitted after some time.

\n
if (cluster.isMaster) {\n  const worker = cluster.fork();\n  let timeout;\n\n  worker.on('listening', (address) => {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(() => {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', () => {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  const net = require('net');\n  const server = net.createServer((socket) => {\n    // Connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', (msg) => {\n    if (msg === 'shutdown') {\n      // Initiate graceful close of any connections to server\n    }\n  });\n}\n
" }, { "textRaw": "`worker.isConnected()`", "type": "method", "name": "isConnected", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This function returns true if the worker is connected to its master via its\nIPC channel, false otherwise. A worker is connected to its master after it\nhas been created. It is disconnected after the 'disconnect' event is emitted.

" }, { "textRaw": "`worker.isDead()`", "type": "method", "name": "isDead", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.

\n
const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('fork', (worker) => {\n    console.log('worker is dead:', worker.isDead());\n  });\n\n  cluster.on('exit', (worker, code, signal) => {\n    console.log('worker is dead:', worker.isDead());\n  });\n} else {\n  // Workers can share any TCP connection. In this case, it is an HTTP server.\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end(`Current process\\n ${process.pid}`);\n    process.kill(process.pid);\n  }).listen(8000);\n}\n
" }, { "textRaw": "`worker.kill([signal])`", "type": "method", "name": "kill", "meta": { "added": [ "v0.9.12" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`signal` {string} Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`", "name": "signal", "type": "string", "desc": "Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`" } ] } ], "desc": "

This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.

\n

Because kill() attempts to gracefully disconnect the worker process, it is\nsusceptible to waiting indefinitely for the disconnect to complete. For example,\nif the worker enters an infinite loop, a graceful disconnect will never occur.\nIf the graceful disconnect behavior is not needed, use worker.process.kill().

\n

Causes .exitedAfterDisconnect to be set.

\n

This method is aliased as worker.destroy() for backward compatibility.

\n

In a worker, process.kill() exists, but it is not this function;\nit is kill().

" }, { "textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`", "type": "method", "name": "send", "meta": { "added": [ "v0.7.0" ], "changes": [ { "version": "v4.0.0", "pr-url": "https://github.com/nodejs/node/pull/2620", "description": "The `callback` parameter is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle}", "name": "sendHandle", "type": "Handle" }, { "textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", "name": "options", "type": "Object", "desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", "options": [ { "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", "name": "keepOpen", "type": "boolean", "default": "`false`", "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Send a message to a worker or master, optionally with a handle.

\n

In the master this sends a message to a specific worker. It is identical to\nChildProcess.send().

\n

In a worker this sends a message to the master. It is identical to\nprocess.send().

\n

This example will echo back all messages from the master:

\n
if (cluster.isMaster) {\n  const worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', (msg) => {\n    process.send(msg);\n  });\n}\n
" } ], "properties": [ { "textRaw": "`exitedAfterDisconnect` {boolean}", "type": "boolean", "name": "exitedAfterDisconnect", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

This property is true if the worker exited due to .kill() or\n.disconnect(). If the worker exited any other way, it is false. If the\nworker has not exited, it is undefined.

\n

The boolean worker.exitedAfterDisconnect allows distinguishing between\nvoluntary and accidental exit, the master may choose not to respawn a worker\nbased on this value.

\n
cluster.on('exit', (worker, code, signal) => {\n  if (worker.exitedAfterDisconnect === true) {\n    console.log('Oh, it was just voluntary – no need to worry');\n  }\n});\n\n// kill worker\nworker.kill();\n
" }, { "textRaw": "`id` {number}", "type": "number", "name": "id", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers.

" }, { "textRaw": "`process` {ChildProcess}", "type": "ChildProcess", "name": "process", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "

All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.

\n

See: Child Process module.

\n

Workers will call process.exit(0) if the 'disconnect' event occurs\non process and .exitedAfterDisconnect is not true. This protects against\naccidental disconnection.

" } ] } ], "events": [ { "textRaw": "Event: `'disconnect'`", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.9" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" } ], "desc": "

Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).

\n

There may be a delay between the 'disconnect' and 'exit' events. These\nevents can be used to detect if the process is stuck in a cleanup or if there\nare long-living connections.

\n
cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n
" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v0.7.9" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" }, { "textRaw": "`code` {number} The exit code, if it exited normally.", "name": "code", "type": "number", "desc": "The exit code, if it exited normally." }, { "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.", "name": "signal", "type": "string", "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed." } ], "desc": "

When any of the workers die the cluster module will emit the 'exit' event.

\n

This can be used to restart the worker by calling .fork() again.

\n
cluster.on('exit', (worker, code, signal) => {\n  console.log('worker %d died (%s). restarting...',\n              worker.process.pid, signal || code);\n  cluster.fork();\n});\n
\n

See child_process event: 'exit'.

" }, { "textRaw": "Event: `'fork'`", "type": "event", "name": "fork", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" } ], "desc": "

When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create a custom timeout.

\n
const timeouts = [];\nfunction errorMsg() {\n  console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});\n
" }, { "textRaw": "Event: `'listening'`", "type": "event", "name": "listening", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" }, { "textRaw": "`address` {Object}", "name": "address", "type": "Object" } ], "desc": "

After calling listen() from a worker, when the 'listening' event is emitted\non the server a 'listening' event will also be emitted on cluster in the\nmaster.

\n

The event handler is executed with two arguments, the worker contains the\nworker object and the address object contains the following connection\nproperties: address, port and addressType. This is very useful if the\nworker is listening on more than one address.

\n
cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});\n
\n

The addressType is one of:

\n" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v2.5.0" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5361", "description": "The `worker` parameter is passed now; see below for details." } ] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" }, { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`handle` {undefined|Object}", "name": "handle", "type": "undefined|Object" } ], "desc": "

Emitted when the cluster master receives a message from any worker.

\n

See child_process event: 'message'.

" }, { "textRaw": "Event: `'online'`", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" } ], "desc": "

After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.

\n
cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});\n
" }, { "textRaw": "Event: `'setup'`", "type": "event", "name": "setup", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "params": [ { "textRaw": "`settings` {Object}", "name": "settings", "type": "Object" } ], "desc": "

Emitted every time .setupMaster() is called.

\n

The settings object is the cluster.settings object at the time\n.setupMaster() was called and is advisory only, since multiple calls to\n.setupMaster() can be made in a single tick.

\n

If accuracy is important, use cluster.settings.

" } ], "methods": [ { "textRaw": "`cluster.disconnect([callback])`", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Called when all workers are disconnected and handles are closed.", "name": "callback", "type": "Function", "desc": "Called when all workers are disconnected and handles are closed." } ] } ], "desc": "

Calls .disconnect() on each worker in cluster.workers.

\n

When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.

\n

The method takes an optional callback argument which will be called when\nfinished.

\n

This can only be called from the master process.

" }, { "textRaw": "`cluster.fork([env])`", "type": "method", "name": "fork", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {cluster.Worker}", "name": "return", "type": "cluster.Worker" }, "params": [ { "textRaw": "`env` {Object} Key/value pairs to add to worker process environment.", "name": "env", "type": "Object", "desc": "Key/value pairs to add to worker process environment." } ] } ], "desc": "

Spawn a new worker process.

\n

This can only be called from the master process.

" }, { "textRaw": "`cluster.setupMaster([settings])`", "type": "method", "name": "setupMaster", "meta": { "added": [ "v0.7.1" ], "changes": [ { "version": "v6.4.0", "pr-url": "https://github.com/nodejs/node/pull/7838", "description": "The `stdio` option is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`settings` {Object} See [`cluster.settings`][].", "name": "settings", "type": "Object", "desc": "See [`cluster.settings`][]." } ] } ], "desc": "

setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.

\n

Any settings changes only affect future calls to .fork() and have no\neffect on workers that are already running.

\n

The only attribute of a worker that cannot be set via .setupMaster() is\nthe env passed to .fork().

\n

The defaults above apply to the first call only; the defaults for later\ncalls are the current values at the time of cluster.setupMaster() is called.

\n
const cluster = require('cluster');\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true\n});\ncluster.fork(); // https worker\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'http']\n});\ncluster.fork(); // http worker\n
\n

This can only be called from the master process.

" } ], "properties": [ { "textRaw": "`isMaster` {boolean}", "type": "boolean", "name": "isMaster", "meta": { "added": [ "v0.8.1" ], "changes": [] }, "desc": "

True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.

" }, { "textRaw": "`isWorker` {boolean}", "type": "boolean", "name": "isWorker", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "desc": "

True if the process is not a master (it is the negation of cluster.isMaster).

" }, { "textRaw": "`cluster.schedulingPolicy`", "name": "schedulingPolicy", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "desc": "

The scheduling policy, either cluster.SCHED_RR for round-robin or\ncluster.SCHED_NONE to leave it to the operating system. This is a\nglobal setting and effectively frozen once either the first worker is spawned,\nor .setupMaster() is called, whichever comes first.

\n

SCHED_RR is the default on all operating systems except Windows.\nWindows will change to SCHED_RR once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.

\n

cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are 'rr' and 'none'.

" }, { "textRaw": "`settings` {Object}", "type": "Object", "name": "settings", "meta": { "added": [ "v0.7.1" ], "changes": [ { "version": "v12.16.0", "pr-url": "https://github.com/nodejs/node/pull/30162", "description": "The `serialization` option is supported now." }, { "version": "v9.5.0", "pr-url": "https://github.com/nodejs/node/pull/18399", "description": "The `cwd` option is supported now." }, { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/17412", "description": "The `windowsHide` option is supported now." }, { "version": "v8.2.0", "pr-url": "https://github.com/nodejs/node/pull/14140", "description": "The `inspectPort` option is supported now." }, { "version": "v6.4.0", "pr-url": "https://github.com/nodejs/node/pull/7838", "description": "The `stdio` option is supported now." } ] }, "options": [ { "textRaw": "`execArgv` {string[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`.", "name": "execArgv", "type": "string[]", "default": "`process.execArgv`", "desc": "List of string arguments passed to the Node.js executable." }, { "textRaw": "`exec` {string} File path to worker file. **Default:** `process.argv[1]`.", "name": "exec", "type": "string", "default": "`process.argv[1]`", "desc": "File path to worker file." }, { "textRaw": "`args` {string[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`.", "name": "args", "type": "string[]", "default": "`process.argv.slice(2)`", "desc": "String arguments passed to worker." }, { "textRaw": "`cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process).", "name": "cwd", "type": "string", "default": "`undefined` (inherits from parent process)", "desc": "Current working directory of the worker process." }, { "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization for `child_process`][] for more details. **Default:** `false`.", "name": "serialization", "type": "string", "default": "`false`", "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization for `child_process`][] for more details." }, { "textRaw": "`silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false`.", "name": "silent", "type": "boolean", "default": "`false`", "desc": "Whether or not to send output to parent's stdio." }, { "textRaw": "`stdio` {Array} Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`.", "name": "stdio", "type": "Array", "desc": "Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`." }, { "textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2).)", "name": "uid", "type": "number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2).)", "name": "gid", "type": "number", "desc": "Sets the group identity of the process. (See setgid(2).)" }, { "textRaw": "`inspectPort` {number|Function} Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`.", "name": "inspectPort", "type": "number|Function", "desc": "Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`." }, { "textRaw": "`windowsHide` {boolean} Hide the forked processes console window that would normally be created on Windows systems. **Default:** `false`.", "name": "windowsHide", "type": "boolean", "default": "`false`", "desc": "Hide the forked processes console window that would normally be created on Windows systems." } ], "desc": "

After calling .setupMaster() (or .fork()) this settings object will\ncontain the settings, including the default values.

\n

This object is not intended to be changed or set manually.

" }, { "textRaw": "`worker` {Object}", "type": "Object", "name": "worker", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "

A reference to the current worker object. Not available in the master process.

\n
const cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n
" }, { "textRaw": "`workers` {Object}", "type": "Object", "name": "workers", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "

A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.

\n

A worker is removed from cluster.workers after the worker has disconnected\nand exited. The order between these two events cannot be determined in\nadvance. However, it is guaranteed that the removal from the cluster.workers\nlist happens before last 'disconnect' or 'exit' event is emitted.

\n
// Go through all workers\nfunction eachWorker(callback) {\n  for (const id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\n});\n
\n

Using the worker's unique id is the easiest way to locate the worker.

\n
socket.on('data', (id) => {\n  const worker = cluster.workers[id];\n});\n
" } ], "type": "module", "displayName": "Cluster" } ] }