{
  "type": "module",
  "source": "doc/api/cluster.md",
  "modules": [
    {
      "textRaw": "Cluster",
      "name": "cluster",
      "introduced_in": "v0.10.0",
      "type": "module",
      "stability": 2,
      "stabilityText": "Stable",
      "desc": "<p>Clusters of Node.js processes can be used to run multiple instances of Node.js\nthat can distribute workloads among their application threads. When process\nisolation is not needed, use the <a href=\"worker_threads.html\"><code>worker_threads</code></a> module instead, which\nallows running multiple application threads within a single Node.js instance.</p>\n<p>The cluster module allows easy creation of child processes that all share\nserver ports.</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\nimport http from 'node:http';\nimport { availableParallelism } from 'node:os';\nimport process from 'node:process';\n\nconst numCPUs = availableParallelism();\n\nif (cluster.isPrimary) {\n  console.log(`Primary ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i &#x3C; 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</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\nconst http = require('node:http');\nconst numCPUs = require('node:os').availableParallelism();\n\nif (cluster.isPrimary) {\n  console.log(`Primary ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i &#x3C; 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</code></pre>\n<p>Running Node.js will now share port 8000 between the workers:</p>\n<pre><code class=\"language-console\">$ node server.js\nPrimary 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n</code></pre>\n<p>On Windows, it is not yet possible to set up a named pipe server in a worker.</p>",
      "miscs": [
        {
          "textRaw": "How it works",
          "name": "How it works",
          "type": "misc",
          "desc": "<p>The worker processes are spawned using the <a href=\"child_process.html#child_processforkmodulepath-args-options\"><code>child_process.fork()</code></a> method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.</p>\n<p>The cluster module supports two methods of distributing incoming\nconnections.</p>\n<p>The first one (and the default one on all platforms except Windows)\nis the round-robin approach, where the primary 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.</p>\n<p>The second approach is where the primary process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.</p>\n<p>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.</p>\n<p>Because <code>server.listen()</code> hands off most of the work to the primary\nprocess, there are three cases where the behavior between a normal\nNode.js process and a cluster worker differs:</p>\n<ol>\n<li><code>server.listen({fd: 7})</code> Because the message is passed to the primary,\nfile descriptor 7 <strong>in the parent</strong> 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.</li>\n<li><code>server.listen(handle)</code> Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the primary\nprocess.</li>\n<li><code>server.listen(0)</code> 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 <code>listen(0)</code>. 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.</li>\n</ol>\n<p>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.</p>\n<p>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.</p>\n<p>Although a primary use case for the <code>node:cluster</code> module is networking, it can\nalso be used for other use cases requiring worker processes.</p>"
        }
      ],
      "classes": [
        {
          "textRaw": "Class: `Worker`",
          "name": "Worker",
          "type": "class",
          "meta": {
            "added": [
              "v0.7.0"
            ],
            "changes": []
          },
          "desc": "<ul>\n<li>Extends: <a href=\"events.html#class-eventemitter\"><code>&#x3C;EventEmitter></code></a></li>\n</ul>\n<p>A <code>Worker</code> object contains all public information and method about a worker.\nIn the primary it can be obtained using <code>cluster.workers</code>. In a worker\nit can be obtained using <code>cluster.worker</code>.</p>",
          "events": [
            {
              "textRaw": "Event: `'disconnect'`",
              "name": "disconnect",
              "type": "event",
              "meta": {
                "added": [
                  "v0.7.7"
                ],
                "changes": []
              },
              "params": [],
              "desc": "<p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n</code></pre>"
            },
            {
              "textRaw": "Event: `'error'`",
              "name": "error",
              "type": "event",
              "meta": {
                "added": [
                  "v0.7.3"
                ],
                "changes": []
              },
              "params": [],
              "desc": "<p>This event is the same as the one provided by <a href=\"child_process.html#child_processforkmodulepath-args-options\"><code>child_process.fork()</code></a>.</p>\n<p>Within a worker, <code>process.on('error')</code> may also be used.</p>"
            },
            {
              "textRaw": "Event: `'exit'`",
              "name": "exit",
              "type": "event",
              "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": "<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\n\nif (cluster.isPrimary) {\n  const worker = cluster.fork();\n  worker.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</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\n\nif (cluster.isPrimary) {\n  const worker = cluster.fork();\n  worker.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</code></pre>"
            },
            {
              "textRaw": "Event: `'listening'`",
              "name": "listening",
              "type": "event",
              "meta": {
                "added": [
                  "v0.7.0"
                ],
                "changes": []
              },
              "params": [
                {
                  "textRaw": "`address` {Object}",
                  "name": "address",
                  "type": "Object"
                }
              ],
              "desc": "<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-mjs\">cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n</code></pre>\n<pre><code class=\"language-cjs\">cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n</code></pre>\n<p>It is not emitted in the worker.</p>"
            },
            {
              "textRaw": "Event: `'message'`",
              "name": "message",
              "type": "event",
              "meta": {
                "added": [
                  "v0.7.0"
                ],
                "changes": []
              },
              "params": [
                {
                  "textRaw": "`message` {Object}",
                  "name": "message",
                  "type": "Object"
                },
                {
                  "textRaw": "`handle` {undefined|Object}",
                  "name": "handle",
                  "type": "undefined|Object"
                }
              ],
              "desc": "<p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p>\n<p>Within a worker, <code>process.on('message')</code> may also be used.</p>\n<p>See <a href=\"process.html#event-message\"><code>process</code> event: <code>'message'</code></a>.</p>\n<p>Here is an example using the message system. It keeps a count in the primary\nprocess of the number of HTTP requests received by the workers:</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\nimport http from 'node:http';\nimport { availableParallelism } from 'node:os';\nimport process from 'node:process';\n\nif (cluster.isPrimary) {\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 &#x26;&#x26; msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  const numCPUs = availableParallelism();\n  for (let i = 0; i &#x3C; 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 primary about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\nconst http = require('node:http');\nconst numCPUs = require('node:os').availableParallelism();\n\nif (cluster.isPrimary) {\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 &#x26;&#x26; msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  for (let i = 0; i &#x3C; 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 primary about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n</code></pre>"
            },
            {
              "textRaw": "Event: `'online'`",
              "name": "online",
              "type": "event",
              "meta": {
                "added": [
                  "v0.7.0"
                ],
                "changes": []
              },
              "params": [],
              "desc": "<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">cluster.fork().on('online', () => {\n  // Worker is online\n});\n</code></pre>\n<p>It is not emitted in the worker.</p>"
            }
          ],
          "methods": [
            {
              "textRaw": "`worker.disconnect()`",
              "name": "disconnect",
              "type": "method",
              "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": [
                {
                  "params": [],
                  "return": {
                    "textRaw": "Returns: {cluster.Worker} A reference to `worker`.",
                    "name": "return",
                    "type": "cluster.Worker",
                    "desc": "A reference to `worker`."
                  }
                }
              ],
              "desc": "<p>In a worker, this function will close all servers, wait for the <code>'close'</code> event\non those servers, and then disconnect the IPC channel.</p>\n<p>In the primary, an internal message is sent to the worker causing it to call\n<code>.disconnect()</code> on itself.</p>\n<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p>\n<p>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 <a href=\"net.html#event-close\"><code>server.close()</code></a>, the IPC channel to the worker will close allowing it\nto die gracefully.</p>\n<p>The above applies <em>only</em> to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.</p>\n<p>In a worker, <code>process.disconnect</code> exists, but it is not this function;\nit is <a href=\"child_process.html#subprocessdisconnect\"><code>disconnect()</code></a>.</p>\n<p>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 <code>'disconnect'</code> event has not been emitted after some time.</p>\n<pre><code class=\"language-js\">if (cluster.isPrimary) {\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('node: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</code></pre>"
            },
            {
              "textRaw": "`worker.isConnected()`",
              "name": "isConnected",
              "type": "method",
              "meta": {
                "added": [
                  "v0.11.14"
                ],
                "changes": []
              },
              "signatures": [
                {
                  "params": []
                }
              ],
              "desc": "<p>This function returns <code>true</code> if the worker is connected to its primary via its\nIPC channel, <code>false</code> otherwise. A worker is connected to its primary after it\nhas been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p>"
            },
            {
              "textRaw": "`worker.isDead()`",
              "name": "isDead",
              "type": "method",
              "meta": {
                "added": [
                  "v0.11.14"
                ],
                "changes": []
              },
              "signatures": [
                {
                  "params": []
                }
              ],
              "desc": "<p>This function returns <code>true</code> if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns <code>false</code>.</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\nimport http from 'node:http';\nimport { availableParallelism } from 'node:os';\nimport process from 'node:process';\n\nconst numCPUs = availableParallelism();\n\nif (cluster.isPrimary) {\n  console.log(`Primary ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i &#x3C; 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</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\nconst http = require('node:http');\nconst numCPUs = require('node:os').availableParallelism();\n\nif (cluster.isPrimary) {\n  console.log(`Primary ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i &#x3C; 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</code></pre>"
            },
            {
              "textRaw": "`worker.kill([signal])`",
              "name": "kill",
              "type": "method",
              "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",
                      "default": "`'SIGTERM'`",
                      "desc": "Name of the kill signal to send to the worker process.",
                      "optional": true
                    }
                  ]
                }
              ],
              "desc": "<p>This function will kill the worker. In the primary worker, it does this by\ndisconnecting the <code>worker.process</code>, and once disconnected, killing with\n<code>signal</code>. In the worker, it does it by killing the process with <code>signal</code>.</p>\n<p>The <code>kill()</code> function kills the worker process without waiting for a graceful\ndisconnect, it has the same behavior as <code>worker.process.kill()</code>.</p>\n<p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.</p>\n<p>In a worker, <code>process.kill()</code> exists, but it is not this function;\nit is <a href=\"process.html#processkillpid-signal\"><code>kill()</code></a>.</p>"
            },
            {
              "textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`",
              "name": "send",
              "type": "method",
              "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": [
                {
                  "params": [
                    {
                      "textRaw": "`message` {Object}",
                      "name": "message",
                      "type": "Object"
                    },
                    {
                      "textRaw": "`sendHandle` {Handle}",
                      "name": "sendHandle",
                      "type": "Handle",
                      "optional": true
                    },
                    {
                      "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."
                        }
                      ],
                      "optional": true
                    },
                    {
                      "textRaw": "`callback` {Function}",
                      "name": "callback",
                      "type": "Function",
                      "optional": true
                    }
                  ],
                  "return": {
                    "textRaw": "Returns: {boolean}",
                    "name": "return",
                    "type": "boolean"
                  }
                }
              ],
              "desc": "<p>Send a message to a worker or primary, optionally with a handle.</p>\n<p>In the primary, this sends a message to a specific worker. It is identical to\n<a href=\"child_process.html#subprocesssendmessage-sendhandle-options-callback\"><code>ChildProcess.send()</code></a>.</p>\n<p>In a worker, this sends a message to the primary. It is identical to\n<code>process.send()</code>.</p>\n<p>This example will echo back all messages from the primary:</p>\n<pre><code class=\"language-js\">if (cluster.isPrimary) {\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</code></pre>"
            }
          ],
          "properties": [
            {
              "textRaw": "Type: {boolean}",
              "name": "exitedAfterDisconnect",
              "type": "boolean",
              "meta": {
                "added": [
                  "v6.0.0"
                ],
                "changes": []
              },
              "desc": "<p>This property is <code>true</code> if the worker exited due to <code>.disconnect()</code>.\nIf the worker exited any other way, it is <code>false</code>. If the\nworker has not exited, it is <code>undefined</code>.</p>\n<p>The boolean <a href=\"#workerexitedafterdisconnect\"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between\nvoluntary and accidental exit, the primary may choose not to respawn a worker\nbased on this value.</p>\n<pre><code class=\"language-js\">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</code></pre>"
            },
            {
              "textRaw": "Type: {integer}",
              "name": "id",
              "type": "integer",
              "meta": {
                "added": [
                  "v0.8.0"
                ],
                "changes": []
              },
              "desc": "<p>Each new worker is given its own unique id, this id is stored in the\n<code>id</code>.</p>\n<p>While a worker is alive, this is the key that indexes it in\n<code>cluster.workers</code>.</p>"
            },
            {
              "textRaw": "Type: {ChildProcess}",
              "name": "process",
              "type": "ChildProcess",
              "meta": {
                "added": [
                  "v0.7.0"
                ],
                "changes": []
              },
              "desc": "<p>All workers are created using <a href=\"child_process.html#child_processforkmodulepath-args-options\"><code>child_process.fork()</code></a>, the returned object\nfrom this function is stored as <code>.process</code>. In a worker, the global <code>process</code>\nis stored.</p>\n<p>See: <a href=\"child_process.html#child_processforkmodulepath-args-options\">Child Process module</a>.</p>\n<p>Workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs\non <code>process</code> and <code>.exitedAfterDisconnect</code> is not <code>true</code>. This protects against\naccidental disconnection.</p>"
            }
          ]
        }
      ],
      "events": [
        {
          "textRaw": "Event: `'disconnect'`",
          "name": "disconnect",
          "type": "event",
          "meta": {
            "added": [
              "v0.7.9"
            ],
            "changes": []
          },
          "params": [
            {
              "textRaw": "`worker` {cluster.Worker}",
              "name": "worker",
              "type": "cluster.Worker"
            }
          ],
          "desc": "<p>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\n<code>worker.disconnect()</code>).</p>\n<p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These\nevents can be used to detect if the process is stuck in a cleanup or if there\nare long-living connections.</p>\n<pre><code class=\"language-js\">cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n</code></pre>"
        },
        {
          "textRaw": "Event: `'exit'`",
          "name": "exit",
          "type": "event",
          "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": "<p>When any of the workers die the cluster module will emit the <code>'exit'</code> event.</p>\n<p>This can be used to restart the worker by calling <a href=\"#clusterforkenv\"><code>.fork()</code></a> again.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>See <a href=\"child_process.html#event-exit\"><code>child_process</code> event: <code>'exit'</code></a>.</p>"
        },
        {
          "textRaw": "Event: `'fork'`",
          "name": "fork",
          "type": "event",
          "meta": {
            "added": [
              "v0.7.0"
            ],
            "changes": []
          },
          "params": [
            {
              "textRaw": "`worker` {cluster.Worker}",
              "name": "worker",
              "type": "cluster.Worker"
            }
          ],
          "desc": "<p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event.\nThis can be used to log worker activity, and create a custom timeout.</p>\n<pre><code class=\"language-js\">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</code></pre>"
        },
        {
          "textRaw": "Event: `'listening'`",
          "name": "listening",
          "type": "event",
          "meta": {
            "added": [
              "v0.7.0"
            ],
            "changes": []
          },
          "params": [
            {
              "textRaw": "`worker` {cluster.Worker}",
              "name": "worker",
              "type": "cluster.Worker"
            },
            {
              "textRaw": "`address` {Object}",
              "name": "address",
              "type": "Object"
            }
          ],
          "desc": "<p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted\non the server, a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the\nprimary.</p>\n<p>The event handler is executed with two arguments, the <code>worker</code> contains the\nworker object and the <code>address</code> object contains the following connection\nproperties: <code>address</code>, <code>port</code>, and <code>addressType</code>. This is very useful if the\nworker is listening on more than one address.</p>\n<pre><code class=\"language-js\">cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});\n</code></pre>\n<p>The <code>addressType</code> is one of:</p>\n<ul>\n<li><code>4</code> (TCPv4)</li>\n<li><code>6</code> (TCPv6)</li>\n<li><code>-1</code> (Unix domain socket)</li>\n<li><code>'udp4'</code> or <code>'udp6'</code> (UDPv4 or UDPv6)</li>\n</ul>"
        },
        {
          "textRaw": "Event: `'message'`",
          "name": "message",
          "type": "event",
          "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": "<p>Emitted when the cluster primary receives a message from any worker.</p>\n<p>See <a href=\"child_process.html#event-message\"><code>child_process</code> event: <code>'message'</code></a>.</p>"
        },
        {
          "textRaw": "Event: `'online'`",
          "name": "online",
          "type": "event",
          "meta": {
            "added": [
              "v0.7.0"
            ],
            "changes": []
          },
          "params": [
            {
              "textRaw": "`worker` {cluster.Worker}",
              "name": "worker",
              "type": "cluster.Worker"
            }
          ],
          "desc": "<p>After forking a new worker, the worker should respond with an online message.\nWhen the primary receives an online message it will emit this event.\nThe difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the\nprimary forks a worker, and <code>'online'</code> is emitted when the worker is running.</p>\n<pre><code class=\"language-js\">cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});\n</code></pre>"
        },
        {
          "textRaw": "Event: `'setup'`",
          "name": "setup",
          "type": "event",
          "meta": {
            "added": [
              "v0.7.1"
            ],
            "changes": []
          },
          "params": [
            {
              "textRaw": "`settings` {Object}",
              "name": "settings",
              "type": "Object"
            }
          ],
          "desc": "<p>Emitted every time <a href=\"#clustersetupprimarysettings\"><code>.setupPrimary()</code></a> is called.</p>\n<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time\n<a href=\"#clustersetupprimarysettings\"><code>.setupPrimary()</code></a> was called and is advisory only, since multiple calls to\n<a href=\"#clustersetupprimarysettings\"><code>.setupPrimary()</code></a> can be made in a single tick.</p>\n<p>If accuracy is important, use <code>cluster.settings</code>.</p>"
        }
      ],
      "methods": [
        {
          "textRaw": "`cluster.disconnect([callback])`",
          "name": "disconnect",
          "type": "method",
          "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.",
                  "optional": true
                }
              ]
            }
          ],
          "desc": "<p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>.</p>\n<p>When they are disconnected all internal handles will be closed, allowing the\nprimary process to die gracefully if no other event is waiting.</p>\n<p>The method takes an optional callback argument which will be called when\nfinished.</p>\n<p>This can only be called from the primary process.</p>"
        },
        {
          "textRaw": "`cluster.fork([env])`",
          "name": "fork",
          "type": "method",
          "meta": {
            "added": [
              "v0.6.0"
            ],
            "changes": []
          },
          "signatures": [
            {
              "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
                }
              ],
              "return": {
                "textRaw": "Returns: {cluster.Worker}",
                "name": "return",
                "type": "cluster.Worker"
              }
            }
          ],
          "desc": "<p>Spawn a new worker process.</p>\n<p>This can only be called from the primary process.</p>"
        },
        {
          "textRaw": "`cluster.setupMaster([settings])`",
          "name": "setupMaster",
          "type": "method",
          "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."
              }
            ],
            "deprecated": [
              "v16.0.0"
            ]
          },
          "stability": 0,
          "stabilityText": "Deprecated",
          "signatures": [
            {
              "params": [
                {
                  "name": "settings",
                  "optional": true
                }
              ]
            }
          ],
          "desc": "<p>Deprecated alias for <a href=\"#clustersetupprimarysettings\"><code>.setupPrimary()</code></a>.</p>"
        },
        {
          "textRaw": "`cluster.setupPrimary([settings])`",
          "name": "setupPrimary",
          "type": "method",
          "meta": {
            "added": [
              "v16.0.0"
            ],
            "changes": []
          },
          "signatures": [
            {
              "params": [
                {
                  "textRaw": "`settings` {Object} See `cluster.settings`.",
                  "name": "settings",
                  "type": "Object",
                  "desc": "See `cluster.settings`.",
                  "optional": true
                }
              ]
            }
          ],
          "desc": "<p><code>setupPrimary</code> is used to change the default 'fork' behavior. Once called,\nthe settings will be present in <code>cluster.settings</code>.</p>\n<p>Any settings changes only affect future calls to <a href=\"#clusterforkenv\"><code>.fork()</code></a> and have no\neffect on workers that are already running.</p>\n<p>The only attribute of a worker that cannot be set via <code>.setupPrimary()</code> is\nthe <code>env</code> passed to <a href=\"#clusterforkenv\"><code>.fork()</code></a>.</p>\n<p>The defaults above apply to the first call only; the defaults for later\ncalls are the current values at the time of <code>cluster.setupPrimary()</code> is called.</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\n\ncluster.setupPrimary({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true,\n});\ncluster.fork(); // https worker\ncluster.setupPrimary({\n  exec: 'worker.js',\n  args: ['--use', 'http'],\n});\ncluster.fork(); // http worker\n</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\n\ncluster.setupPrimary({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true,\n});\ncluster.fork(); // https worker\ncluster.setupPrimary({\n  exec: 'worker.js',\n  args: ['--use', 'http'],\n});\ncluster.fork(); // http worker\n</code></pre>\n<p>This can only be called from the primary process.</p>"
        }
      ],
      "properties": [
        {
          "textRaw": "`cluster.isMaster`",
          "name": "isMaster",
          "type": "property",
          "meta": {
            "added": [
              "v0.8.1"
            ],
            "changes": [],
            "deprecated": [
              "v16.0.0"
            ]
          },
          "stability": 0,
          "stabilityText": "Deprecated",
          "desc": "<p>Deprecated alias for <a href=\"#clusterisprimary\"><code>cluster.isPrimary</code></a>.</p>"
        },
        {
          "textRaw": "Type: {boolean}",
          "name": "isPrimary",
          "type": "boolean",
          "meta": {
            "added": [
              "v16.0.0"
            ],
            "changes": []
          },
          "desc": "<p>True if the process is a primary. This is determined\nby the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is\nundefined, then <code>isPrimary</code> is <code>true</code>.</p>"
        },
        {
          "textRaw": "Type: {boolean}",
          "name": "isWorker",
          "type": "boolean",
          "meta": {
            "added": [
              "v0.6.0"
            ],
            "changes": []
          },
          "desc": "<p>True if the process is not a primary (it is the negation of <code>cluster.isPrimary</code>).</p>"
        },
        {
          "textRaw": "`cluster.schedulingPolicy`",
          "name": "schedulingPolicy",
          "type": "property",
          "meta": {
            "added": [
              "v0.11.2"
            ],
            "changes": []
          },
          "desc": "<p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or\n<code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a\nglobal setting and effectively frozen once either the first worker is spawned,\nor <a href=\"#clustersetupprimarysettings\"><code>.setupPrimary()</code></a> is called, whichever comes first.</p>\n<p><code>SCHED_RR</code> is the default on all operating systems except Windows.\nWindows will change to <code>SCHED_RR</code> once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.</p>\n<p><code>cluster.schedulingPolicy</code> can also be set through the\n<code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid\nvalues are <code>'rr'</code> and <code>'none'</code>.</p>"
        },
        {
          "textRaw": "Type: {Object}",
          "name": "settings",
          "type": "Object",
          "meta": {
            "added": [
              "v0.7.1"
            ],
            "changes": [
              {
                "version": [
                  "v13.2.0",
                  "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."
              }
            ]
          },
          "desc": "<p>After calling <a href=\"#clustersetupprimarysettings\"><code>.setupPrimary()</code></a> (or <a href=\"#clusterforkenv\"><code>.fork()</code></a>) this settings object will\ncontain the settings, including the default values.</p>\n<p>This object is not intended to be changed or set manually.</p>",
          "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`. See `child_process.spawn()`'s `stdio`.",
              "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`. See `child_process.spawn()`'s `stdio`."
            },
            {
              "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 primary'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 primary'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."
            }
          ]
        },
        {
          "textRaw": "Type: {Object}",
          "name": "worker",
          "type": "Object",
          "meta": {
            "added": [
              "v0.7.0"
            ],
            "changes": []
          },
          "desc": "<p>A reference to the current worker object. Not available in the primary process.</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\n\nif (cluster.isPrimary) {\n  console.log('I am primary');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\n\nif (cluster.isPrimary) {\n  console.log('I am primary');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n</code></pre>"
        },
        {
          "textRaw": "Type: {Object}",
          "name": "workers",
          "type": "Object",
          "meta": {
            "added": [
              "v0.7.0"
            ],
            "changes": []
          },
          "desc": "<p>A hash that stores the active worker objects, keyed by <code>id</code> field. This makes it\neasy to loop through all the workers. It is only available in the primary\nprocess.</p>\n<p>A worker is removed from <code>cluster.workers</code> after the worker has disconnected\n<em>and</em> exited. The order between these two events cannot be determined in\nadvance. However, it is guaranteed that the removal from the <code>cluster.workers</code>\nlist happens before the last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>\n<pre><code class=\"language-mjs\">import cluster from 'node:cluster';\n\nfor (const worker of Object.values(cluster.workers)) {\n  worker.send('big announcement to all workers');\n}\n</code></pre>\n<pre><code class=\"language-cjs\">const cluster = require('node:cluster');\n\nfor (const worker of Object.values(cluster.workers)) {\n  worker.send('big announcement to all workers');\n}\n</code></pre>"
        }
      ],
      "displayName": "Cluster"
    }
  ]
}