{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"cluster","path":"/cluster","type":"module","module":"cluster","title":"Cluster","introducedIn":"v0.10.0","sourceLink":{"path":"lib/cluster.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/cluster.js"},"stability":{"index":"2","description":"Stable"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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 [`worker_threads`](worker_threads.html) module instead, which\nallows running multiple application threads within a single Node.js instance.\n\nThe cluster module allows easy creation of child processes that all share\nserver ports.\n\n```mjs\nimport 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 < 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\n```cjs\nconst 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 < 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\nRunning Node.js will now share port 8000 between the workers:\n\n```console\n$ node server.js\nPrimary 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n```\n\nOn Windows, it is not yet possible to set up a named pipe server in a worker.","summary":"Clusters of Node.js processes can be used to run multiple instances of Node.js that can distribute workloads among their application threads. When process isolation is not needed, use the `worker_threads` module instead, which allows running multiple application threads within a single Node.js instance.","examples":[{"language":"mjs","displayName":null,"code":"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 < 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}"},{"language":"cjs","displayName":null,"code":"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 < 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}"},{"language":"console","displayName":null,"code":"$ node server.js\nPrimary 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started"}],"children":[{"kind":"section","id":"how-it-works","name":"How it works","title":"How it works","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The worker processes are spawned using the [`child_process.fork()`](child_process.html#child_processforkmodulepath-args-options) method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\nThe cluster module supports two methods of distributing incoming\nconnections.\n\nThe 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.\n\nThe second approach is where the primary process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.\n\nThe 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\nBecause `server.listen()` 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:\n\n1. `server.listen({fd: 7})` Because the message is passed to the primary,\n   file descriptor 7 **in the parent** will be listened on, and the\n   handle passed to the worker, rather than listening to the worker's\n   idea of what the number 7 file descriptor references.\n2. `server.listen(handle)` Listening on handles explicitly will cause\n   the worker to use the supplied handle, rather than talk to the primary\n   process.\n3. `server.listen(0)` Normally, this will cause servers to listen on a\n   random port. However, in a cluster, each worker will receive the\n   same \"random\" port each time they do `listen(0)`. In essence, the\n   port is random the first time, but predictable thereafter. To listen\n   on a unique port, generate a port number based on the cluster worker ID.\n\nNode.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\nBecause 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\nAlthough a primary use case for the `node:cluster` module is networking, it can\nalso be used for other use cases requiring worker processes.","summary":"The worker processes are spawned using the `child_process.fork()` method, so that they can communicate with the parent via IPC and pass server handles back and forth.","examples":[],"children":[]},{"kind":"class","id":"class-worker","name":"Worker","title":"Class: `Worker`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":{"text":"EventEmitter","links":[{"name":"EventEmitter","href":"events.html#class-eventemitter","start":0,"end":12}]},"description":"A `Worker` object contains all public information and method about a worker.\nIn the primary it can be obtained using `cluster.workers`. In a worker\nit can be obtained using `cluster.worker`.","summary":"A `Worker` object contains all public information and method about a worker. In the primary it can be obtained using `cluster.workers`. In a worker it can be obtained using `cluster.worker`.","examples":[],"children":[{"kind":"event","id":"event-disconnect","name":"disconnect","title":"Event: `'disconnect'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.7"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"Similar to the `cluster.on('disconnect')` event, but specific to this worker.\n\n```js\ncluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n```","summary":"Similar to the `cluster.on('disconnect')` event, but specific to this worker.","examples":[{"language":"js","displayName":null,"code":"cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});"}],"children":[]},{"kind":"event","id":"event-error","name":"error","title":"Event: `'error'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.3"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"This event is the same as the one provided by [`child_process.fork()`](child_process.html#child_processforkmodulepath-args-options).\n\nWithin a worker, `process.on('error')` may also be used.","summary":"This event is the same as the one provided by `child_process.fork()`.","examples":[],"children":[]},{"kind":"event","id":"event-exit","name":"exit","title":"Event: `'exit'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.2"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"code","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The exit code, if it exited normally.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"signal","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The name of the signal (e.g. `'SIGHUP'`) that caused\nthe process to be killed.","default":null,"optional":false,"rest":false,"properties":[]}],"description":"Similar to the `cluster.on('exit')` event, but specific to this worker.\n\n```mjs\nimport 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```\n\n```cjs\nconst 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```","summary":"Similar to the `cluster.on('exit')` event, but specific to this worker.","examples":[{"language":"mjs","displayName":null,"code":"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}"},{"language":"cjs","displayName":null,"code":"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}"}],"children":[]},{"kind":"event","id":"event-listening","name":"listening","title":"Event: `'listening'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"address","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"Similar to the `cluster.on('listening')` event, but specific to this worker.\n\n```mjs\ncluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n```\n\n```cjs\ncluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n```\n\nIt is not emitted in the worker.","summary":"Similar to the `cluster.on('listening')` event, but specific to this worker.","examples":[{"language":"mjs","displayName":null,"code":"cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});"},{"language":"cjs","displayName":null,"code":"cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});"}],"children":[]},{"kind":"event","id":"event-message","name":"message","title":"Event: `'message'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"message","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"handle","type":{"text":"undefined | Object","links":[{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":0,"end":9},{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":12,"end":18}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"Similar to the `'message'` event of `cluster`, but specific to this worker.\n\nWithin a worker, `process.on('message')` may also be used.\n\nSee [`process` event: `'message'`](process.html#event-message).\n\nHere 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:\n\n```mjs\nimport 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 && 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 < 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```\n\n```cjs\nconst 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 && msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\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 primary about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n```","summary":"Similar to the `'message'` event of `cluster`, but specific to this worker.","examples":[{"language":"mjs","displayName":null,"code":"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 && 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 < 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}"},{"language":"cjs","displayName":null,"code":"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 && msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\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 primary about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}"}],"children":[]},{"kind":"event","id":"event-online","name":"online","title":"Event: `'online'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"Similar to the `cluster.on('online')` event, but specific to this worker.\n\n```js\ncluster.fork().on('online', () => {\n  // Worker is online\n});\n```\n\nIt is not emitted in the worker.","summary":"Similar to the `cluster.on('online')` event, but specific to this worker.","examples":[{"language":"js","displayName":null,"code":"cluster.fork().on('online', () => {\n  // Worker is online\n});"}],"children":[]},{"kind":"method","id":"workerdisconnect","name":"disconnect","title":"`worker.disconnect()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.7"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v7.3.0"],"prUrl":"https://github.com/nodejs/node/pull/10019","commit":null,"description":"This method now returns a reference to `worker`."}],"signature":{"parameters":[],"returns":{"type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"A reference to `worker`."}},"description":"In a worker, this function will close all servers, wait for the `'close'` event\non those servers, and then disconnect the IPC channel.\n\nIn the primary, an internal message is sent to the worker causing it to call\n`.disconnect()` on itself.\n\nCauses `.exitedAfterDisconnect` to be set.\n\nAfter 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()`](net.html#event-close), the IPC channel to the worker will close allowing it\nto die gracefully.\n\nThe 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\nIn a worker, `process.disconnect` exists, but it is not this function;\nit is [`disconnect()`](child_process.html#subprocessdisconnect).\n\nBecause 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\n```js\nif (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```","summary":"In a worker, this function will close all servers, wait for the `'close'` event on those servers, and then disconnect the IPC channel.","examples":[{"language":"js","displayName":null,"code":"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}"}],"children":[]},{"kind":"property","id":"workerexitedafterdisconnect","name":"exitedAfterDisconnect","title":"`worker.exitedAfterDisconnect`","scope":"module","overloadOf":null,"stability":null,"added":["v6.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"This property is `true` if the worker exited due to `.disconnect()`.\nIf the worker exited any other way, it is `false`. If the\nworker has not exited, it is `undefined`.\n\nThe boolean [`worker.exitedAfterDisconnect`](#workerexitedafterdisconnect) allows distinguishing between\nvoluntary and accidental exit, the primary may choose not to respawn a worker\nbased on this value.\n\n```js\ncluster.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```","summary":"This property is `true` if the worker exited due to `.disconnect()`. If the worker exited any other way, it is `false`. If the worker has not exited, it is `undefined`.","examples":[{"language":"js","displayName":null,"code":"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();"}],"children":[]},{"kind":"property","id":"workerid","name":"id","title":"`worker.id`","scope":"module","overloadOf":null,"stability":null,"added":["v0.8.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"default":null,"description":"Each new worker is given its own unique id, this id is stored in the\n`id`.\n\nWhile a worker is alive, this is the key that indexes it in\n`cluster.workers`.","summary":"Each new worker is given its own unique id, this id is stored in the `id`.","examples":[],"children":[]},{"kind":"method","id":"workerisconnected","name":"isConnected","title":"`worker.isConnected()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.14"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"This function returns `true` if the worker is connected to its primary via its\nIPC channel, `false` otherwise. A worker is connected to its primary after it\nhas been created. It is disconnected after the `'disconnect'` event is emitted.","summary":"This function returns `true` if the worker is connected to its primary via its IPC channel, `false` otherwise. A worker is connected to its primary after it has been created. It is disconnected after the `'disconnect'` event is emitted.","examples":[],"children":[]},{"kind":"method","id":"workerisdead","name":"isDead","title":"`worker.isDead()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.14"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"This function returns `true` if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns `false`.\n\n```mjs\nimport 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 < 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```\n\n```cjs\nconst 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 < 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```","summary":"This function returns `true` if the worker's process has terminated (either because of exiting or being signaled). Otherwise, it returns `false`.","examples":[{"language":"mjs","displayName":null,"code":"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 < 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}"},{"language":"cjs","displayName":null,"code":"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 < 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}"}],"children":[]},{"kind":"method","id":"workerkillsignal","name":"kill","title":"`worker.kill([signal])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.12"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"signal","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Name of the kill signal to send to the worker\nprocess.","default":"'SIGTERM'","optional":true,"rest":false,"properties":[]}],"returns":null},"description":"This function will kill the worker. In the primary worker, it does this by\ndisconnecting the `worker.process`, and once disconnected, killing with\n`signal`. In the worker, it does it by killing the process with `signal`.\n\nThe `kill()` function kills the worker process without waiting for a graceful\ndisconnect, it has the same behavior as `worker.process.kill()`.\n\nThis method is aliased as `worker.destroy()` for backwards compatibility.\n\nIn a worker, `process.kill()` exists, but it is not this function;\nit is [`kill()`](process.html#processkillpid-signal).","summary":"This function will kill the worker. In the primary worker, it does this by disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`.","examples":[],"children":[]},{"kind":"property","id":"workerprocess","name":"process","title":"`worker.process`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"ChildProcess","links":[{"name":"ChildProcess","href":"child_process.html#class-childprocess","start":0,"end":12}]},"default":null,"description":"All workers are created using [`child_process.fork()`](child_process.html#child_processforkmodulepath-args-options), the returned object\nfrom this function is stored as `.process`. In a worker, the global `process`\nis stored.\n\nSee: [Child Process module](child_process.html#child_processforkmodulepath-args-options).\n\nWorkers will call `process.exit(0)` if the `'disconnect'` event occurs\non `process` and `.exitedAfterDisconnect` is not `true`. This protects against\naccidental disconnection.","summary":"All workers are created using `child_process.fork()`, the returned object from this function is stored as `.process`. In a worker, the global `process` is stored.","examples":[],"children":[]},{"kind":"method","id":"workersendmessage-sendhandle-options-callback","name":"send","title":"`worker.send(message[, sendHandle[, options]][, callback])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v4.0.0"],"prUrl":"https://github.com/nodejs/node/pull/2620","commit":null,"description":"The `callback` parameter is supported now."}],"signature":{"parameters":[{"name":"message","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"sendHandle","type":{"text":"Handle","links":[{"name":"Handle","href":"net.html#serverlistenhandle-backlog-callback","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The `options` argument, if present, is an object used to\nparameterize the sending of certain types of handles. `options` supports\nthe following properties:","default":null,"optional":true,"rest":false,"properties":[{"name":"keepOpen","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"A value that can be used when passing instances of\n`net.Socket`. When `true`, the socket is kept open in the sending process.","default":"false","optional":true,"rest":false,"properties":[]}]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"Send a message to a worker or primary, optionally with a handle.\n\nIn the primary, this sends a message to a specific worker. It is identical to\n[`ChildProcess.send()`](child_process.html#subprocesssendmessage-sendhandle-options-callback).\n\nIn a worker, this sends a message to the primary. It is identical to\n`process.send()`.\n\nThis example will echo back all messages from the primary:\n\n```js\nif (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```","summary":"Send a message to a worker or primary, optionally with a handle.","examples":[{"language":"js","displayName":null,"code":"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}"}],"children":[]}]},{"kind":"event","id":"event-disconnect-1","name":"disconnect","title":"Event: `'disconnect'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.9"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"worker","type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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`worker.disconnect()`).\n\nThere 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\n```js\ncluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n```","summary":"Emitted after the worker IPC channel has disconnected. This can occur when a worker exits gracefully, is killed, or is disconnected manually (such as with `worker.disconnect()`).","examples":[{"language":"js","displayName":null,"code":"cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});"}],"children":[]},{"kind":"event","id":"event-exit-1","name":"exit","title":"Event: `'exit'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.9"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"worker","type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"code","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The exit code, if it exited normally.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"signal","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The name of the signal (e.g. `'SIGHUP'`) that caused\nthe process to be killed.","default":null,"optional":false,"rest":false,"properties":[]}],"description":"When any of the workers die the cluster module will emit the `'exit'` event.\n\nThis can be used to restart the worker by calling [`.fork()`](#clusterforkenv) again.\n\n```js\ncluster.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\nSee [`child_process` event: `'exit'`](child_process.html#event-exit).","summary":"When any of the workers die the cluster module will emit the `'exit'` event.","examples":[{"language":"js","displayName":null,"code":"cluster.on('exit', (worker, code, signal) => {\n  console.log('worker %d died (%s). restarting...',\n              worker.process.pid, signal || code);\n  cluster.fork();\n});"}],"children":[]},{"kind":"event","id":"event-fork","name":"fork","title":"Event: `'fork'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"worker","type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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\n```js\nconst 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```","summary":"When a new worker is forked the cluster module will emit a `'fork'` event. This can be used to log worker activity, and create a custom timeout.","examples":[{"language":"js","displayName":null,"code":"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});"}],"children":[]},{"kind":"event","id":"event-listening-1","name":"listening","title":"Event: `'listening'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"worker","type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"address","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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\nprimary.\n\nThe 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\n```js\ncluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});\n```\n\nThe `addressType` is one of:\n\n* `4` (TCPv4)\n* `6` (TCPv6)\n* `-1` (Unix domain socket)\n* `'udp4'` or `'udp6'` (UDPv4 or UDPv6)","summary":"After calling `listen()` from a worker, when the `'listening'` event is emitted on the server, a `'listening'` event will also be emitted on `cluster` in the primary.","examples":[{"language":"js","displayName":null,"code":"cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});"}],"children":[]},{"kind":"event","id":"event-message-1","name":"message","title":"Event: `'message'`","scope":"module","overloadOf":null,"stability":null,"added":["v2.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v6.0.0"],"prUrl":"https://github.com/nodejs/node/pull/5361","commit":null,"description":"The `worker` parameter is passed now; see below for details."}],"parameters":[{"name":"worker","type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"message","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"handle","type":{"text":"undefined | Object","links":[{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":0,"end":9},{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":12,"end":18}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"Emitted when the cluster primary receives a message from any worker.\n\nSee [`child_process` event: `'message'`](child_process.html#event-message).","summary":"Emitted when the cluster primary receives a message from any worker.","examples":[],"children":[]},{"kind":"event","id":"event-online-1","name":"online","title":"Event: `'online'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"worker","type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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 `'fork'` and `'online'` is that fork is emitted when the\nprimary forks a worker, and `'online'` is emitted when the worker is running.\n\n```js\ncluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});\n```","summary":"After forking a new worker, the worker should respond with an online message. When the primary receives an online message it will emit this event. The difference between `'fork'` and `'online'` is that fork is emitted when the primary forks a worker, and `'online'` is emitted when the worker is running.","examples":[{"language":"js","displayName":null,"code":"cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});"}],"children":[]},{"kind":"event","id":"event-setup","name":"setup","title":"Event: `'setup'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"settings","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"Emitted every time [`.setupPrimary()`](#clustersetupprimarysettings) is called.\n\nThe `settings` object is the `cluster.settings` object at the time\n[`.setupPrimary()`](#clustersetupprimarysettings) was called and is advisory only, since multiple calls to\n[`.setupPrimary()`](#clustersetupprimarysettings) can be made in a single tick.\n\nIf accuracy is important, use `cluster.settings`.","summary":"Emitted every time `.setupPrimary()` is called.","examples":[],"children":[]},{"kind":"method","id":"clusterdisconnectcallback","name":"disconnect","title":"`cluster.disconnect([callback])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.7"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Called when all workers are disconnected and handles are\nclosed.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"Calls `.disconnect()` on each worker in `cluster.workers`.\n\nWhen they are disconnected all internal handles will be closed, allowing the\nprimary process to die gracefully if no other event is waiting.\n\nThe method takes an optional callback argument which will be called when\nfinished.\n\nThis can only be called from the primary process.","summary":"Calls `.disconnect()` on each worker in `cluster.workers`.","examples":[],"children":[]},{"kind":"method","id":"clusterforkenv","name":"fork","title":"`cluster.fork([env])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.6.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"env","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Key/value pairs to add to worker process environment.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"cluster.Worker","links":[{"name":"cluster.Worker","href":"cluster.html#class-clusterworker","start":0,"end":14}]},"description":""}},"description":"Spawn a new worker process.\n\nThis can only be called from the primary process.","summary":"Spawn a new worker process.","examples":[],"children":[]},{"kind":"property","id":"clusterismaster","name":"isMaster","title":"`cluster.isMaster`","scope":"module","overloadOf":null,"stability":{"index":"0","description":"Deprecated"},"added":["v0.8.1"],"deprecated":["v16.0.0"],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"Deprecated alias for [`cluster.isPrimary`](#clusterisprimary).","summary":"Deprecated alias for `cluster.isPrimary`.","examples":[],"children":[]},{"kind":"property","id":"clusterisprimary","name":"isPrimary","title":"`cluster.isPrimary`","scope":"module","overloadOf":null,"stability":null,"added":["v16.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"True if the process is a primary. This is determined\nby the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is\nundefined, then `isPrimary` is `true`.","summary":"True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is undefined, then `isPrimary` is `true`.","examples":[],"children":[]},{"kind":"property","id":"clusterisworker","name":"isWorker","title":"`cluster.isWorker`","scope":"module","overloadOf":null,"stability":null,"added":["v0.6.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"True if the process is not a primary (it is the negation of `cluster.isPrimary`).","summary":"True if the process is not a primary (it is the negation of `cluster.isPrimary`).","examples":[],"children":[]},{"kind":"property","id":"clusterschedulingpolicy","name":"schedulingPolicy","title":"`cluster.schedulingPolicy`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.2"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"The scheduling policy, either `cluster.SCHED_RR` for round-robin or\n`cluster.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 [`.setupPrimary()`](#clustersetupprimarysettings) is called, whichever comes first.\n\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\n`cluster.schedulingPolicy` can also be set through the\n`NODE_CLUSTER_SCHED_POLICY` environment variable. Valid\nvalues are `'rr'` and `'none'`.","summary":"The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a global setting and effectively frozen once either the first worker is spawned, or `.setupPrimary()` is called, whichever comes first.","examples":[],"children":[]},{"kind":"property","id":"clustersettings","name":"settings","title":"`cluster.settings`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v13.2.0","v12.16.0"],"prUrl":"https://github.com/nodejs/node/pull/30162","commit":null,"description":"The `serialization` option is supported now."},{"versions":["v9.5.0"],"prUrl":"https://github.com/nodejs/node/pull/18399","commit":null,"description":"The `cwd` option is supported now."},{"versions":["v9.4.0"],"prUrl":"https://github.com/nodejs/node/pull/17412","commit":null,"description":"The `windowsHide` option is supported now."},{"versions":["v8.2.0"],"prUrl":"https://github.com/nodejs/node/pull/14140","commit":null,"description":"The `inspectPort` option is supported now."},{"versions":["v6.4.0"],"prUrl":"https://github.com/nodejs/node/pull/7838","commit":null,"description":"The `stdio` option is supported now."}],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"After calling [`.setupPrimary()`](#clustersetupprimarysettings) (or [`.fork()`](#clusterforkenv)) this settings object will\ncontain the settings, including the default values.\n\nThis object is not intended to be changed or set manually.","summary":"After calling `.setupPrimary()` (or `.fork()`) this settings object will contain the settings, including the default values.","examples":[],"children":[]},{"kind":"method","id":"clustersetupmastersettings","name":"setupMaster","title":"`cluster.setupMaster([settings])`","scope":"module","overloadOf":null,"stability":{"index":"0","description":"Deprecated"},"added":["v0.7.1"],"deprecated":["v16.0.0"],"removed":[],"napiVersion":[],"changes":[{"versions":["v6.4.0"],"prUrl":"https://github.com/nodejs/node/pull/7838","commit":null,"description":"The `stdio` option is supported now."}],"signature":{"parameters":[{"name":"settings","type":null,"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"Deprecated alias for [`.setupPrimary()`](#clustersetupprimarysettings).","summary":"Deprecated alias for `.setupPrimary()`.","examples":[],"children":[]},{"kind":"method","id":"clustersetupprimarysettings","name":"setupPrimary","title":"`cluster.setupPrimary([settings])`","scope":"module","overloadOf":null,"stability":null,"added":["v16.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"settings","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"See [`cluster.settings`](#clustersettings).","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"`setupPrimary` is used to change the default 'fork' behavior. Once called,\nthe settings will be present in `cluster.settings`.\n\nAny settings changes only affect future calls to [`.fork()`](#clusterforkenv) and have no\neffect on workers that are already running.\n\nThe only attribute of a worker that cannot be set via `.setupPrimary()` is\nthe `env` passed to [`.fork()`](#clusterforkenv).\n\nThe defaults above apply to the first call only; the defaults for later\ncalls are the current values at the time of `cluster.setupPrimary()` is called.\n\n```mjs\nimport 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```\n\n```cjs\nconst 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```\n\nThis can only be called from the primary process.","summary":"`setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`.","examples":[{"language":"mjs","displayName":null,"code":"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"},{"language":"cjs","displayName":null,"code":"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"}],"children":[]},{"kind":"property","id":"clusterworker","name":"worker","title":"`cluster.worker`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"A reference to the current worker object. Not available in the primary process.\n\n```mjs\nimport 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```\n\n```cjs\nconst 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```","summary":"A reference to the current worker object. Not available in the primary process.","examples":[{"language":"mjs","displayName":null,"code":"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}"},{"language":"cjs","displayName":null,"code":"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}"}],"children":[]},{"kind":"property","id":"clusterworkers","name":"workers","title":"`cluster.workers`","scope":"module","overloadOf":null,"stability":null,"added":["v0.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"A hash that stores the active worker objects, keyed by `id` field. This makes it\neasy to loop through all the workers. It is only available in the primary\nprocess.\n\nA worker is removed from `cluster.workers` after the worker has disconnected\n*and* 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 the last `'disconnect'` or `'exit'` event is emitted.\n\n```mjs\nimport cluster from 'node:cluster';\n\nfor (const worker of Object.values(cluster.workers)) {\n  worker.send('big announcement to all workers');\n}\n```\n\n```cjs\nconst cluster = require('node:cluster');\n\nfor (const worker of Object.values(cluster.workers)) {\n  worker.send('big announcement to all workers');\n}\n```","summary":"A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process.","examples":[{"language":"mjs","displayName":null,"code":"import cluster from 'node:cluster';\n\nfor (const worker of Object.values(cluster.workers)) {\n  worker.send('big announcement to all workers');\n}"},{"language":"cjs","displayName":null,"code":"const cluster = require('node:cluster');\n\nfor (const worker of Object.values(cluster.workers)) {\n  worker.send('big announcement to all workers');\n}"}],"children":[]}]}