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

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 you to easily create child processes that\nall share server 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

Please note that on Windows, it is not yet possible to set up a named pipe\nserver in a worker.

\n", "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. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
  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. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
  6. \n
\n

There is no routing logic in Node.js, or in your program, and no shared\nstate between the workers. Therefore, it is important to design your\nprogram such that it does not rely too heavily on in-memory data objects\nfor things like sessions and login.

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on your 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 for you, however. It is your\nresponsibility to manage the worker pool for your application's needs.

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

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.

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

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

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

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

\n

In a worker you can also use process.on('error').

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.11.2" ] }, "params": [], "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
\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.7.0" ] }, "params": [], "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.

\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

Similar to the cluster.on('message') event, but specific to this worker. In a\nworker you can also use process.on('message').

\n

See process event: 'message'.

\n

As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:

\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
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ] }, "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.

\n", "params": [] } ], "methods": [ { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Worker} A reference to `worker`. ", "name": "return", "type": "Worker", "desc": "A reference to `worker`." }, "params": [] }, { "params": [] } ], "desc": "

In a worker, this function will close all servers, wait for the 'close' event on\nthose 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

Note that 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 to\ndie 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

Note that 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
\n" }, { "textRaw": "worker.isConnected()", "type": "method", "name": "isConnected", "meta": { "added": [ "v0.11.14" ] }, "desc": "

This function returns true if the worker is connected to its master via its IPC\nchannel, false otherwise. A worker is connected to its master after it's been\ncreated. It is disconnected after the 'disconnect' event is emitted.

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

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

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "meta": { "added": [ "v0.9.12" ] }, "signatures": [ { "params": [ { "textRaw": "`signal` {String} Name of the kill signal to send to the worker process. ", "name": "signal", "type": "String", "desc": "Name of the kill signal to send to the worker process.", "optional": true, "default": "'SIGTERM'" } ] }, { "params": [ { "name": "signal", "optional": true, "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

Causes .exitedAfterDisconnect to be set.

\n

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

\n

Note that in a worker, process.kill() exists, but it is not this function,\nit is kill.

\n" }, { "textRaw": "worker.send(message[, sendHandle][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.7.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: Boolean ", "name": "return", "desc": "Boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle} ", "name": "sendHandle", "type": "Handle", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "callback", "optional": true } ] } ], "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
\n" } ], "properties": [ { "textRaw": "`exitedAfterDisconnect` {Boolean} ", "type": "Boolean", "name": "exitedAfterDisconnect", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Set by calling .kill() or .disconnect(). Until then, it is undefined.

\n

The boolean worker.exitedAfterDisconnect lets you distinguish between voluntary\nand accidental exit, the master may choose not to respawn a worker based on\nthis 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
\n" }, { "textRaw": "`id` {Number} ", "type": "Number", "name": "id", "meta": { "added": [ "v0.8.0" ] }, "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

\n" }, { "textRaw": "`process` {ChildProcess} ", "type": "ChildProcess", "name": "process", "meta": { "added": [ "v0.7.0" ] }, "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

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

\n" }, { "textRaw": "worker.suicide", "name": "suicide", "meta": { "added": [ "v0.7.0" ], "deprecated": [ "v6.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`worker.exitedAfterDisconnect`][] instead.", "desc": "

An alias to worker.exitedAfterDisconnect.

\n

Set by calling .kill() or .disconnect(). Until then, it is undefined.

\n

The boolean worker.suicide lets you distinguish between voluntary\nand accidental exit, the master may choose not to respawn a worker based on\nthis value.

\n
cluster.on('exit', (worker, code, signal) => {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just voluntary – no need to worry');\n  }\n});\n\n// kill worker\nworker.kill();\n
\n

This API only exists for backwards compatibility and will be removed in the\nfuture.

\n" } ] } ], "events": [ { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.9" ] }, "params": [], "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 events\ncan be used to detect if the process is stuck in a cleanup or if there are\nlong-living connections.

\n
cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n
\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.7.9" ] }, "params": [], "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'.

\n" }, { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "meta": { "added": [ "v0.7.0" ] }, "params": [], "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 your own 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
\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

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

\n

The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non 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\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

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

\n

See child_process event: 'message'.

\n

Before Node.js v6.0, this event emitted only the message and the handle,\nbut not the worker object, contrary to what the documentation stated.

\n

If you need to support older versions and don't need the worker object,\nyou can work around the discrepancy by checking the number of arguments:

\n
cluster.on('message', (worker, message, handle) => {\n  if (arguments.length === 2) {\n    handle = message;\n    message = worker;\n    worker = undefined;\n  }\n  // ...\n});\n
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ] }, "params": [], "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
\n" }, { "textRaw": "Event: 'setup'", "type": "event", "name": "setup", "meta": { "added": [ "v0.7.1" ] }, "params": [], "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.

\n" } ], "methods": [ { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "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", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "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 finished.

\n

This can only be called from the master process.

\n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "meta": { "added": [ "v0.6.0" ] }, "signatures": [ { "return": { "textRaw": "return {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.", "optional": true } ] }, { "params": [ { "name": "env", "optional": true } ] } ], "desc": "

Spawn a new worker process.

\n

This can only be called from the master process.

\n" }, { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "meta": { "added": [ "v0.7.1" ] }, "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." }, { "textRaw": "`stdio` {Array} Configures the stdio of forked processes. When this option is provided, it overrides `silent`. ", "name": "stdio", "type": "Array", "desc": "Configures the stdio of forked processes. When this option is provided, it overrides `silent`." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "

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

\n

Note that:

\n\n

Example:

\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.

\n" } ], "properties": [ { "textRaw": "`isMaster` {Boolean} ", "type": "Boolean", "name": "isMaster", "meta": { "added": [ "v0.8.1" ] }, "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.

\n" }, { "textRaw": "`isWorker` {Boolean} ", "type": "Boolean", "name": "isWorker", "meta": { "added": [ "v0.6.0" ] }, "desc": "

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

\n" }, { "textRaw": "cluster.schedulingPolicy", "name": "schedulingPolicy", "meta": { "added": [ "v0.11.2" ] }, "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 you spawn the first worker\nor call cluster.setupMaster(), whatever 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".

\n" }, { "textRaw": "`settings` {Object} ", "type": "Object", "name": "settings", "meta": { "added": [ "v0.7.1" ] }, "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the Node.js executable. (Default=`process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "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", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "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).)" } ], "desc": "

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

\n

This object is not supposed to be changed or set manually, by you.

\n" }, { "textRaw": "`worker` {Object} ", "type": "Object", "name": "worker", "meta": { "added": [ "v0.7.0" ] }, "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
\n" }, { "textRaw": "`workers` {Object} ", "type": "Object", "name": "workers", "meta": { "added": [ "v0.7.0" ] }, "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 and\nexited. The order between these two events cannot be determined in advance.\nHowever, it is guaranteed that the removal from the cluster.workers list happens\nbefore 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

Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.

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