• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1{
2  "type": "module",
3  "source": "doc/api/cluster.md",
4  "modules": [
5    {
6      "textRaw": "Cluster",
7      "name": "cluster",
8      "introduced_in": "v0.10.0",
9      "stability": 2,
10      "stabilityText": "Stable",
11      "desc": "<p><strong>Source Code:</strong> <a href=\"https://github.com/nodejs/node/blob/v14.20.1/lib/cluster.js\">lib/cluster.js</a></p>\n<p>A single instance of Node.js runs in a single thread. To take advantage of\nmulti-core systems, the user will sometimes want to launch a cluster of Node.js\nprocesses to handle the load.</p>\n<p>The cluster module allows easy creation of child processes that all share\nserver ports.</p>\n<pre><code class=\"language-js\">const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i &#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\nMaster 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>",
12      "miscs": [
13        {
14          "textRaw": "How it works",
15          "name": "How it works",
16          "type": "misc",
17          "desc": "<p>The worker processes are spawned using the <a href=\"child_process.html#child_process_child_process_fork_modulepath_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 master process listens on a\nport, accepts new connections and distributes them across the workers\nin a round-robin fashion, with some built-in smarts to avoid\noverloading a worker process.</p>\n<p>The second approach is where the master process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.</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 master\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 master,\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 master\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>cluster</code> module is networking, it can\nalso be used for other use cases requiring worker processes.</p>"
18        }
19      ],
20      "classes": [
21        {
22          "textRaw": "Class: `Worker`",
23          "type": "class",
24          "name": "Worker",
25          "meta": {
26            "added": [
27              "v0.7.0"
28            ],
29            "changes": []
30          },
31          "desc": "<ul>\n<li>Extends: <a href=\"events.html#events_class_eventemitter\" class=\"type\">&lt;EventEmitter&gt;</a></li>\n</ul>\n<p>A <code>Worker</code> object contains all public information and method about a worker.\nIn the master it can be obtained using <code>cluster.workers</code>. In a worker\nit can be obtained using <code>cluster.worker</code>.</p>",
32          "events": [
33            {
34              "textRaw": "Event: `'disconnect'`",
35              "type": "event",
36              "name": "disconnect",
37              "meta": {
38                "added": [
39                  "v0.7.7"
40                ],
41                "changes": []
42              },
43              "params": [],
44              "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>"
45            },
46            {
47              "textRaw": "Event: `'error'`",
48              "type": "event",
49              "name": "error",
50              "meta": {
51                "added": [
52                  "v0.7.3"
53                ],
54                "changes": []
55              },
56              "params": [],
57              "desc": "<p>This event is the same as the one provided by <a href=\"child_process.html#child_process_child_process_fork_modulepath_args_options\"><code>child_process.fork()</code></a>.</p>\n<p>Within a worker, <code>process.on('error')</code> may also be used.</p>"
58            },
59            {
60              "textRaw": "Event: `'exit'`",
61              "type": "event",
62              "name": "exit",
63              "meta": {
64                "added": [
65                  "v0.11.2"
66                ],
67                "changes": []
68              },
69              "params": [
70                {
71                  "textRaw": "`code` {number} The exit code, if it exited normally.",
72                  "name": "code",
73                  "type": "number",
74                  "desc": "The exit code, if it exited normally."
75                },
76                {
77                  "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.",
78                  "name": "signal",
79                  "type": "string",
80                  "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed."
81                }
82              ],
83              "desc": "<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">const worker = cluster.fork();\nworker.on('exit', (code, signal) => {\n  if (signal) {\n    console.log(`worker was killed by signal: ${signal}`);\n  } else if (code !== 0) {\n    console.log(`worker exited with error code: ${code}`);\n  } else {\n    console.log('worker success!');\n  }\n});\n</code></pre>"
84            },
85            {
86              "textRaw": "Event: `'listening'`",
87              "type": "event",
88              "name": "listening",
89              "meta": {
90                "added": [
91                  "v0.7.0"
92                ],
93                "changes": []
94              },
95              "params": [
96                {
97                  "textRaw": "`address` {Object}",
98                  "name": "address",
99                  "type": "Object"
100                }
101              ],
102              "desc": "<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n</code></pre>\n<p>It is not emitted in the worker.</p>"
103            },
104            {
105              "textRaw": "Event: `'message'`",
106              "type": "event",
107              "name": "message",
108              "meta": {
109                "added": [
110                  "v0.7.0"
111                ],
112                "changes": []
113              },
114              "params": [
115                {
116                  "textRaw": "`message` {Object}",
117                  "name": "message",
118                  "type": "Object"
119                },
120                {
121                  "textRaw": "`handle` {undefined|Object}",
122                  "name": "handle",
123                  "type": "undefined|Object"
124                }
125              ],
126              "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#process_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 master\nprocess of the number of HTTP requests received by the workers:</p>\n<pre><code class=\"language-js\">const cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  let numReqs = 0;\n  setInterval(() => {\n    console.log(`numReqs = ${numReqs}`);\n  }, 1000);\n\n  // Count requests\n  function messageHandler(msg) {\n    if (msg.cmd &#x26;&#x26; msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  const numCPUs = require('os').cpus().length;\n  for (let i = 0; i &#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 master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n</code></pre>"
127            },
128            {
129              "textRaw": "Event: `'online'`",
130              "type": "event",
131              "name": "online",
132              "meta": {
133                "added": [
134                  "v0.7.0"
135                ],
136                "changes": []
137              },
138              "params": [],
139              "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>"
140            }
141          ],
142          "methods": [
143            {
144              "textRaw": "`worker.disconnect()`",
145              "type": "method",
146              "name": "disconnect",
147              "meta": {
148                "added": [
149                  "v0.7.7"
150                ],
151                "changes": [
152                  {
153                    "version": "v7.3.0",
154                    "pr-url": "https://github.com/nodejs/node/pull/10019",
155                    "description": "This method now returns a reference to `worker`."
156                  }
157                ]
158              },
159              "signatures": [
160                {
161                  "return": {
162                    "textRaw": "Returns: {cluster.Worker} A reference to `worker`.",
163                    "name": "return",
164                    "type": "cluster.Worker",
165                    "desc": "A reference to `worker`."
166                  },
167                  "params": []
168                }
169              ],
170              "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 master, 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#net_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#child_process_subprocess_disconnect\"><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.isMaster) {\n  const worker = cluster.fork();\n  let timeout;\n\n  worker.on('listening', (address) => {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(() => {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', () => {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  const net = require('net');\n  const server = net.createServer((socket) => {\n    // Connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', (msg) => {\n    if (msg === 'shutdown') {\n      // Initiate graceful close of any connections to server\n    }\n  });\n}\n</code></pre>"
171            },
172            {
173              "textRaw": "`worker.isConnected()`",
174              "type": "method",
175              "name": "isConnected",
176              "meta": {
177                "added": [
178                  "v0.11.14"
179                ],
180                "changes": []
181              },
182              "signatures": [
183                {
184                  "params": []
185                }
186              ],
187              "desc": "<p>This function returns <code>true</code> if the worker is connected to its master via its\nIPC channel, <code>false</code> otherwise. A worker is connected to its master after it\nhas been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p>"
188            },
189            {
190              "textRaw": "`worker.isDead()`",
191              "type": "method",
192              "name": "isDead",
193              "meta": {
194                "added": [
195                  "v0.11.14"
196                ],
197                "changes": []
198              },
199              "signatures": [
200                {
201                  "params": []
202                }
203              ],
204              "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-js\">const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i &#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>"
205            },
206            {
207              "textRaw": "`worker.kill([signal])`",
208              "type": "method",
209              "name": "kill",
210              "meta": {
211                "added": [
212                  "v0.9.12"
213                ],
214                "changes": []
215              },
216              "signatures": [
217                {
218                  "params": [
219                    {
220                      "textRaw": "`signal` {string} Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`",
221                      "name": "signal",
222                      "type": "string",
223                      "desc": "Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`"
224                    }
225                  ]
226                }
227              ],
228              "desc": "<p>This function will kill the worker. In the master, it does this by disconnecting\nthe <code>worker.process</code>, and once disconnected, killing with <code>signal</code>. In the\nworker, it does it by disconnecting the channel, and then exiting with code <code>0</code>.</p>\n<p>Because <code>kill()</code> attempts to gracefully disconnect the worker process, it is\nsusceptible to waiting indefinitely for the disconnect to complete. For example,\nif the worker enters an infinite loop, a graceful disconnect will never occur.\nIf the graceful disconnect behavior is not needed, use <code>worker.process.kill()</code>.</p>\n<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p>\n<p>This method is aliased as <code>worker.destroy()</code> for backward compatibility.</p>\n<p>In a worker, <code>process.kill()</code> exists, but it is not this function;\nit is <a href=\"process.html#process_process_kill_pid_signal\"><code>kill()</code></a>.</p>"
229            },
230            {
231              "textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`",
232              "type": "method",
233              "name": "send",
234              "meta": {
235                "added": [
236                  "v0.7.0"
237                ],
238                "changes": [
239                  {
240                    "version": "v4.0.0",
241                    "pr-url": "https://github.com/nodejs/node/pull/2620",
242                    "description": "The `callback` parameter is supported now."
243                  }
244                ]
245              },
246              "signatures": [
247                {
248                  "return": {
249                    "textRaw": "Returns: {boolean}",
250                    "name": "return",
251                    "type": "boolean"
252                  },
253                  "params": [
254                    {
255                      "textRaw": "`message` {Object}",
256                      "name": "message",
257                      "type": "Object"
258                    },
259                    {
260                      "textRaw": "`sendHandle` {Handle}",
261                      "name": "sendHandle",
262                      "type": "Handle"
263                    },
264                    {
265                      "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:",
266                      "name": "options",
267                      "type": "Object",
268                      "desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
269                      "options": [
270                        {
271                          "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`.",
272                          "name": "keepOpen",
273                          "type": "boolean",
274                          "default": "`false`",
275                          "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process."
276                        }
277                      ]
278                    },
279                    {
280                      "textRaw": "`callback` {Function}",
281                      "name": "callback",
282                      "type": "Function"
283                    }
284                  ]
285                }
286              ],
287              "desc": "<p>Send a message to a worker or master, optionally with a handle.</p>\n<p>In the master this sends a message to a specific worker. It is identical to\n<a href=\"child_process.html#child_process_subprocess_send_message_sendhandle_options_callback\"><code>ChildProcess.send()</code></a>.</p>\n<p>In a worker this sends a message to the master. It is identical to\n<code>process.send()</code>.</p>\n<p>This example will echo back all messages from the master:</p>\n<pre><code class=\"language-js\">if (cluster.isMaster) {\n  const worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', (msg) => {\n    process.send(msg);\n  });\n}\n</code></pre>"
288            }
289          ],
290          "properties": [
291            {
292              "textRaw": "`exitedAfterDisconnect` {boolean}",
293              "type": "boolean",
294              "name": "exitedAfterDisconnect",
295              "meta": {
296                "added": [
297                  "v6.0.0"
298                ],
299                "changes": []
300              },
301              "desc": "<p>This property is <code>true</code> if the worker exited due to <code>.kill()</code> or\n<code>.disconnect()</code>. If 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=\"#cluster_worker_exitedafterdisconnect\"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between\nvoluntary and accidental exit, the master 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>"
302            },
303            {
304              "textRaw": "`id` {number}",
305              "type": "number",
306              "name": "id",
307              "meta": {
308                "added": [
309                  "v0.8.0"
310                ],
311                "changes": []
312              },
313              "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>"
314            },
315            {
316              "textRaw": "`process` {ChildProcess}",
317              "type": "ChildProcess",
318              "name": "process",
319              "meta": {
320                "added": [
321                  "v0.7.0"
322                ],
323                "changes": []
324              },
325              "desc": "<p>All workers are created using <a href=\"child_process.html#child_process_child_process_fork_modulepath_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_process_child_process_fork_modulepath_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>"
326            }
327          ]
328        }
329      ],
330      "events": [
331        {
332          "textRaw": "Event: `'disconnect'`",
333          "type": "event",
334          "name": "disconnect",
335          "meta": {
336            "added": [
337              "v0.7.9"
338            ],
339            "changes": []
340          },
341          "params": [
342            {
343              "textRaw": "`worker` {cluster.Worker}",
344              "name": "worker",
345              "type": "cluster.Worker"
346            }
347          ],
348          "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>"
349        },
350        {
351          "textRaw": "Event: `'exit'`",
352          "type": "event",
353          "name": "exit",
354          "meta": {
355            "added": [
356              "v0.7.9"
357            ],
358            "changes": []
359          },
360          "params": [
361            {
362              "textRaw": "`worker` {cluster.Worker}",
363              "name": "worker",
364              "type": "cluster.Worker"
365            },
366            {
367              "textRaw": "`code` {number} The exit code, if it exited normally.",
368              "name": "code",
369              "type": "number",
370              "desc": "The exit code, if it exited normally."
371            },
372            {
373              "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.",
374              "name": "signal",
375              "type": "string",
376              "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed."
377            }
378          ],
379          "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=\"#cluster_cluster_fork_env\"><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#child_process_event_exit\"><code>child_process</code> event: <code>'exit'</code></a>.</p>"
380        },
381        {
382          "textRaw": "Event: `'fork'`",
383          "type": "event",
384          "name": "fork",
385          "meta": {
386            "added": [
387              "v0.7.0"
388            ],
389            "changes": []
390          },
391          "params": [
392            {
393              "textRaw": "`worker` {cluster.Worker}",
394              "name": "worker",
395              "type": "cluster.Worker"
396            }
397          ],
398          "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>"
399        },
400        {
401          "textRaw": "Event: `'listening'`",
402          "type": "event",
403          "name": "listening",
404          "meta": {
405            "added": [
406              "v0.7.0"
407            ],
408            "changes": []
409          },
410          "params": [
411            {
412              "textRaw": "`worker` {cluster.Worker}",
413              "name": "worker",
414              "type": "cluster.Worker"
415            },
416            {
417              "textRaw": "`address` {Object}",
418              "name": "address",
419              "type": "Object"
420            }
421          ],
422          "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\nmaster.</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> (UDP v4 or v6)</li>\n</ul>"
423        },
424        {
425          "textRaw": "Event: `'message'`",
426          "type": "event",
427          "name": "message",
428          "meta": {
429            "added": [
430              "v2.5.0"
431            ],
432            "changes": [
433              {
434                "version": "v6.0.0",
435                "pr-url": "https://github.com/nodejs/node/pull/5361",
436                "description": "The `worker` parameter is passed now; see below for details."
437              }
438            ]
439          },
440          "params": [
441            {
442              "textRaw": "`worker` {cluster.Worker}",
443              "name": "worker",
444              "type": "cluster.Worker"
445            },
446            {
447              "textRaw": "`message` {Object}",
448              "name": "message",
449              "type": "Object"
450            },
451            {
452              "textRaw": "`handle` {undefined|Object}",
453              "name": "handle",
454              "type": "undefined|Object"
455            }
456          ],
457          "desc": "<p>Emitted when the cluster master receives a message from any worker.</p>\n<p>See <a href=\"child_process.html#child_process_event_message\"><code>child_process</code> event: <code>'message'</code></a>.</p>"
458        },
459        {
460          "textRaw": "Event: `'online'`",
461          "type": "event",
462          "name": "online",
463          "meta": {
464            "added": [
465              "v0.7.0"
466            ],
467            "changes": []
468          },
469          "params": [
470            {
471              "textRaw": "`worker` {cluster.Worker}",
472              "name": "worker",
473              "type": "cluster.Worker"
474            }
475          ],
476          "desc": "<p>After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the\nmaster 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>"
477        },
478        {
479          "textRaw": "Event: `'setup'`",
480          "type": "event",
481          "name": "setup",
482          "meta": {
483            "added": [
484              "v0.7.1"
485            ],
486            "changes": []
487          },
488          "params": [
489            {
490              "textRaw": "`settings` {Object}",
491              "name": "settings",
492              "type": "Object"
493            }
494          ],
495          "desc": "<p>Emitted every time <a href=\"#cluster_cluster_setupmaster_settings\"><code>.setupMaster()</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=\"#cluster_cluster_setupmaster_settings\"><code>.setupMaster()</code></a> was called and is advisory only, since multiple calls to\n<a href=\"#cluster_cluster_setupmaster_settings\"><code>.setupMaster()</code></a> can be made in a single tick.</p>\n<p>If accuracy is important, use <code>cluster.settings</code>.</p>"
496        }
497      ],
498      "methods": [
499        {
500          "textRaw": "`cluster.disconnect([callback])`",
501          "type": "method",
502          "name": "disconnect",
503          "meta": {
504            "added": [
505              "v0.7.7"
506            ],
507            "changes": []
508          },
509          "signatures": [
510            {
511              "params": [
512                {
513                  "textRaw": "`callback` {Function} Called when all workers are disconnected and handles are closed.",
514                  "name": "callback",
515                  "type": "Function",
516                  "desc": "Called when all workers are disconnected and handles are closed."
517                }
518              ]
519            }
520          ],
521          "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\nmaster 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 master process.</p>"
522        },
523        {
524          "textRaw": "`cluster.fork([env])`",
525          "type": "method",
526          "name": "fork",
527          "meta": {
528            "added": [
529              "v0.6.0"
530            ],
531            "changes": []
532          },
533          "signatures": [
534            {
535              "return": {
536                "textRaw": "Returns: {cluster.Worker}",
537                "name": "return",
538                "type": "cluster.Worker"
539              },
540              "params": [
541                {
542                  "textRaw": "`env` {Object} Key/value pairs to add to worker process environment.",
543                  "name": "env",
544                  "type": "Object",
545                  "desc": "Key/value pairs to add to worker process environment."
546                }
547              ]
548            }
549          ],
550          "desc": "<p>Spawn a new worker process.</p>\n<p>This can only be called from the master process.</p>"
551        },
552        {
553          "textRaw": "`cluster.setupMaster([settings])`",
554          "type": "method",
555          "name": "setupMaster",
556          "meta": {
557            "added": [
558              "v0.7.1"
559            ],
560            "changes": [
561              {
562                "version": "v6.4.0",
563                "pr-url": "https://github.com/nodejs/node/pull/7838",
564                "description": "The `stdio` option is supported now."
565              }
566            ]
567          },
568          "signatures": [
569            {
570              "params": [
571                {
572                  "textRaw": "`settings` {Object} See [`cluster.settings`][].",
573                  "name": "settings",
574                  "type": "Object",
575                  "desc": "See [`cluster.settings`][]."
576                }
577              ]
578            }
579          ],
580          "desc": "<p><code>setupMaster</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=\"#cluster_cluster_fork_env\"><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>.setupMaster()</code> is\nthe <code>env</code> passed to <a href=\"#cluster_cluster_fork_env\"><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.setupMaster()</code> is called.</p>\n<pre><code class=\"language-js\">const cluster = require('cluster');\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true\n});\ncluster.fork(); // https worker\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'http']\n});\ncluster.fork(); // http worker\n</code></pre>\n<p>This can only be called from the master process.</p>"
581        }
582      ],
583      "properties": [
584        {
585          "textRaw": "`isMaster` {boolean}",
586          "type": "boolean",
587          "name": "isMaster",
588          "meta": {
589            "added": [
590              "v0.8.1"
591            ],
592            "changes": []
593          },
594          "desc": "<p>True if the process is a master. This is determined\nby the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is\nundefined, then <code>isMaster</code> is <code>true</code>.</p>"
595        },
596        {
597          "textRaw": "`isWorker` {boolean}",
598          "type": "boolean",
599          "name": "isWorker",
600          "meta": {
601            "added": [
602              "v0.6.0"
603            ],
604            "changes": []
605          },
606          "desc": "<p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).</p>"
607        },
608        {
609          "textRaw": "`cluster.schedulingPolicy`",
610          "name": "schedulingPolicy",
611          "meta": {
612            "added": [
613              "v0.11.2"
614            ],
615            "changes": []
616          },
617          "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=\"#cluster_cluster_setupmaster_settings\"><code>.setupMaster()</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>"
618        },
619        {
620          "textRaw": "`settings` {Object}",
621          "type": "Object",
622          "name": "settings",
623          "meta": {
624            "added": [
625              "v0.7.1"
626            ],
627            "changes": [
628              {
629                "version": [
630                  "v13.2.0",
631                  "v12.16.0"
632                ],
633                "pr-url": "https://github.com/nodejs/node/pull/30162",
634                "description": "The `serialization` option is supported now."
635              },
636              {
637                "version": "v9.5.0",
638                "pr-url": "https://github.com/nodejs/node/pull/18399",
639                "description": "The `cwd` option is supported now."
640              },
641              {
642                "version": "v9.4.0",
643                "pr-url": "https://github.com/nodejs/node/pull/17412",
644                "description": "The `windowsHide` option is supported now."
645              },
646              {
647                "version": "v8.2.0",
648                "pr-url": "https://github.com/nodejs/node/pull/14140",
649                "description": "The `inspectPort` option is supported now."
650              },
651              {
652                "version": "v6.4.0",
653                "pr-url": "https://github.com/nodejs/node/pull/7838",
654                "description": "The `stdio` option is supported now."
655              }
656            ]
657          },
658          "options": [
659            {
660              "textRaw": "`execArgv` {string[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`.",
661              "name": "execArgv",
662              "type": "string[]",
663              "default": "`process.execArgv`",
664              "desc": "List of string arguments passed to the Node.js executable."
665            },
666            {
667              "textRaw": "`exec` {string} File path to worker file. **Default:** `process.argv[1]`.",
668              "name": "exec",
669              "type": "string",
670              "default": "`process.argv[1]`",
671              "desc": "File path to worker file."
672            },
673            {
674              "textRaw": "`args` {string[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`.",
675              "name": "args",
676              "type": "string[]",
677              "default": "`process.argv.slice(2)`",
678              "desc": "String arguments passed to worker."
679            },
680            {
681              "textRaw": "`cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process).",
682              "name": "cwd",
683              "type": "string",
684              "default": "`undefined` (inherits from parent process)",
685              "desc": "Current working directory of the worker process."
686            },
687            {
688              "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`.",
689              "name": "serialization",
690              "type": "string",
691              "default": "`false`",
692              "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."
693            },
694            {
695              "textRaw": "`silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false`.",
696              "name": "silent",
697              "type": "boolean",
698              "default": "`false`",
699              "desc": "Whether or not to send output to parent's stdio."
700            },
701            {
702              "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`.",
703              "name": "stdio",
704              "type": "Array",
705              "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`."
706            },
707            {
708              "textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2).)",
709              "name": "uid",
710              "type": "number",
711              "desc": "Sets the user identity of the process. (See setuid(2).)"
712            },
713            {
714              "textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2).)",
715              "name": "gid",
716              "type": "number",
717              "desc": "Sets the group identity of the process. (See setgid(2).)"
718            },
719            {
720              "textRaw": "`inspectPort` {number|Function} Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`.",
721              "name": "inspectPort",
722              "type": "number|Function",
723              "desc": "Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`."
724            },
725            {
726              "textRaw": "`windowsHide` {boolean} Hide the forked processes console window that would normally be created on Windows systems. **Default:** `false`.",
727              "name": "windowsHide",
728              "type": "boolean",
729              "default": "`false`",
730              "desc": "Hide the forked processes console window that would normally be created on Windows systems."
731            }
732          ],
733          "desc": "<p>After calling <a href=\"#cluster_cluster_setupmaster_settings\"><code>.setupMaster()</code></a> (or <a href=\"#cluster_cluster_fork_env\"><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>"
734        },
735        {
736          "textRaw": "`worker` {Object}",
737          "type": "Object",
738          "name": "worker",
739          "meta": {
740            "added": [
741              "v0.7.0"
742            ],
743            "changes": []
744          },
745          "desc": "<p>A reference to the current worker object. Not available in the master process.</p>\n<pre><code class=\"language-js\">const cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n</code></pre>"
746        },
747        {
748          "textRaw": "`workers` {Object}",
749          "type": "Object",
750          "name": "workers",
751          "meta": {
752            "added": [
753              "v0.7.0"
754            ],
755            "changes": []
756          },
757          "desc": "<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it\neasy to loop through all the workers. It is only available in the master\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 last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>\n<pre><code class=\"language-js\">// Go through all workers\nfunction eachWorker(callback) {\n  for (const id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\n});\n</code></pre>\n<p>Using the worker's unique id is the easiest way to locate the worker.</p>\n<pre><code class=\"language-js\">socket.on('data', (id) => {\n  const worker = cluster.workers[id];\n});\n</code></pre>"
758        }
759      ],
760      "type": "module",
761      "displayName": "Cluster"
762    }
763  ]
764}