{
  "source": "doc/api/cluster.markdown",
  "modules": [
    {
      "textRaw": "Cluster",
      "name": "cluster",
      "stability": 1,
      "stabilityText": "Experimental",
      "desc": "<p>A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n</p>\n<p>The cluster module allows you to easily create a network of processes that\nall share server ports.\n\n</p>\n<pre><code>var cluster = require(&#39;cluster&#39;);\nvar http = require(&#39;http&#39;);\nvar numCPUs = require(&#39;os&#39;).cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i &lt; numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on(&#39;exit&#39;, function(worker, code, signal) {\n    console.log(&#39;worker &#39; + worker.process.pid + &#39; died&#39;);\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end(&quot;hello world\\n&quot;);\n  }).listen(8000);\n}</code></pre>\n<p>Running node will now share port 8000 between the workers:\n\n</p>\n<pre><code>% node server.js\nWorker 2438 online\nWorker 2437 online</code></pre>\n<p>This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n</p>\n<p>Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n</p>\n",
      "miscs": [
        {
          "textRaw": "How It Works",
          "name": "How It Works",
          "type": "misc",
          "desc": "<p>The worker processes are spawned using the <code>child_process.fork</code> method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n</p>\n<p>When you call <code>server.listen(...)</code> in a worker, it serializes the\narguments and passes the request to the master process.  If the master\nprocess already has a listening server matching the worker&#39;s\nrequirements, then it passes the handle to the worker.  If it does not\nalready have a listening server matching that requirement, then it will\ncreate one, and pass the handle to the child.\n\n</p>\n<p>This causes potentially surprising behavior in three edge cases:\n\n</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&#39;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.  If the worker already has the handle, then it&#39;s presumed\nthat you know what you are doing.</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 &quot;random&quot; port each time they do <code>listen(0)</code>.  In essence, the\nport is random the first time, but predictable thereafter.  If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.</li>\n</ol>\n<p>When multiple processes are all <code>accept()</code>ing on the same underlying\nresource, the operating system load-balances across them very\nefficiently.  There is no routing logic in Node.js, or in your program,\nand no shared state between the workers.  Therefore, it is important to\ndesign your program such that it does not rely too heavily on in-memory\ndata objects for things like sessions and login.\n\n</p>\n<p>Because workers are all separate processes, they can be killed or\nre-spawned depending on your program&#39;s needs, without affecting other\nworkers.  As long as there are some workers still alive, the server will\ncontinue to accept connections.  Node does not automatically manage the\nnumber of workers for you, however.  It is your responsibility to manage\nthe worker pool for your application&#39;s needs.\n\n</p>\n"
        }
      ],
      "properties": [
        {
          "textRaw": "`settings` {Object} ",
          "name": "settings",
          "options": [
            {
              "textRaw": "`exec` {String} file path to worker file.  (Default=`__filename`) ",
              "name": "exec",
              "default": "__filename",
              "type": "String",
              "desc": "file path to worker file."
            },
            {
              "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ",
              "name": "args",
              "default": "process.argv.slice(2)",
              "type": "Array",
              "desc": "string arguments passed to worker."
            },
            {
              "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ",
              "name": "silent",
              "default": "false",
              "type": "Boolean",
              "desc": "whether or not to send output to parent's stdio."
            }
          ],
          "desc": "<p>All settings set by the <code>.setupMaster</code> is stored in this settings object.\nThis object is not supposed to be changed or set manually, by you.\n\n</p>\n"
        },
        {
          "textRaw": "`isMaster` {Boolean} ",
          "name": "isMaster",
          "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>.\n\n</p>\n"
        },
        {
          "textRaw": "`isWorker` {Boolean} ",
          "name": "isWorker",
          "desc": "<p>This boolean flag is true if the process is a worker forked from a master.\nIf the <code>process.env.NODE_UNIQUE_ID</code> is set to a value, then\n<code>isWorker</code> is <code>true</code>.\n\n</p>\n"
        },
        {
          "textRaw": "`worker` {Object} ",
          "name": "worker",
          "desc": "<p>A reference to the current worker object. Not available in the master process.\n\n</p>\n<pre><code>var cluster = require(&#39;cluster&#39;);\n\nif (cluster.isMaster) {\n  console.log(&#39;I am master&#39;);\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(&#39;I am worker #&#39; + cluster.worker.id);\n}</code></pre>\n"
        },
        {
          "textRaw": "`workers` {Object} ",
          "name": "workers",
          "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.\n\n</p>\n<pre><code>// Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send(&#39;big announcement to all workers&#39;);\n});</code></pre>\n<p>Should you wish to reference a worker over a communication channel, using\nthe worker&#39;s unique id is the easiest way to find the worker.\n\n</p>\n<pre><code>socket.on(&#39;data&#39;, function(id) {\n  var worker = cluster.workers[id];\n});</code></pre>\n"
        }
      ],
      "events": [
        {
          "textRaw": "Event: 'fork'",
          "type": "event",
          "name": "fork",
          "params": [],
          "desc": "<p>When a new worker is forked the cluster module will emit a &#39;fork&#39; event.\nThis can be used to log worker activity, and create you own timeout.\n\n</p>\n<pre><code>var timeouts = [];\nfunction errorMsg() {\n  console.error(&quot;Something must be wrong with the connection ...&quot;);\n}\n\ncluster.on(&#39;fork&#39;, function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on(&#39;listening&#39;, function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on(&#39;exit&#39;, function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});</code></pre>\n"
        },
        {
          "textRaw": "Event: 'online'",
          "type": "event",
          "name": "online",
          "params": [],
          "desc": "<p>After forking a new worker, the worker should respond with a online message.\nWhen the master receives a online message it will emit such event.\nThe difference between &#39;fork&#39; and &#39;online&#39; is that fork is emitted when the\nmaster tries to fork a worker, and &#39;online&#39; is emitted when the worker is\nbeing executed.\n\n</p>\n<pre><code>cluster.on(&#39;online&#39;, function(worker) {\n  console.log(&quot;Yay, the worker responded after it was forked&quot;);\n});</code></pre>\n"
        },
        {
          "textRaw": "Event: 'listening'",
          "type": "event",
          "name": "listening",
          "params": [],
          "desc": "<p>When calling <code>listen()</code> from a worker, a &#39;listening&#39; event is automatically assigned\nto the server instance. When the server is listening a message is send to the master\nwhere the &#39;listening&#39; event is emitted.\n\n</p>\n<p>The event handler is executed with two arguments, the <code>worker</code> contains the worker\nobject and the <code>address</code> object contains the following connection properties:\n<code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the worker is listening\non more than one address.\n\n</p>\n<pre><code>cluster.on(&#39;listening&#39;, function(worker, address) {\n  console.log(&quot;A worker is now connected to &quot; + address.address + &quot;:&quot; + address.port);\n});</code></pre>\n"
        },
        {
          "textRaw": "Event: 'disconnect'",
          "type": "event",
          "name": "disconnect",
          "params": [],
          "desc": "<p>When a workers IPC channel has disconnected this event is emitted. This will happen\nwhen the worker dies, usually after calling <code>.destroy()</code>.\n\n</p>\n<p>When calling <code>.disconnect()</code>, there may be a delay between the\n<code>disconnect</code> and <code>exit</code> events.  This event can be used to detect if\nthe process is stuck in a cleanup or if there are long-living\nconnections.\n\n</p>\n<pre><code>cluster.on(&#39;disconnect&#39;, function(worker) {\n  console.log(&#39;The worker #&#39; + worker.id + &#39; has disconnected&#39;);\n});</code></pre>\n"
        },
        {
          "textRaw": "Event: 'exit'",
          "type": "event",
          "name": "exit",
          "params": [],
          "desc": "<p>When any of the workers die the cluster module will emit the &#39;exit&#39; event.\nThis can be used to restart the worker by calling <code>fork()</code> again.\n\n</p>\n<pre><code>cluster.on(&#39;exit&#39;, function(worker, code, signal) {\n  var exitCode = worker.process.exitCode;\n  console.log(&#39;worker &#39; + worker.process.pid + &#39; died (&#39;+exitCode+&#39;). restarting...&#39;);\n  cluster.fork();\n});</code></pre>\n"
        },
        {
          "textRaw": "Event: 'setup'",
          "type": "event",
          "name": "setup",
          "params": [],
          "desc": "<p>When the <code>.setupMaster()</code> function has been executed this event emits.\nIf <code>.setupMaster()</code> was not executed before <code>fork()</code> this function will\ncall <code>.setupMaster()</code> with no arguments.\n\n</p>\n"
        }
      ],
      "methods": [
        {
          "textRaw": "cluster.setupMaster([settings])",
          "type": "method",
          "name": "setupMaster",
          "signatures": [
            {
              "params": [
                {
                  "textRaw": "`settings` {Object} ",
                  "options": [
                    {
                      "textRaw": "`exec` {String} file path to worker file.  (Default=`__filename`) ",
                      "name": "exec",
                      "default": "__filename",
                      "type": "String",
                      "desc": "file path to worker file."
                    },
                    {
                      "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ",
                      "name": "args",
                      "default": "process.argv.slice(2)",
                      "type": "Array",
                      "desc": "string arguments passed to worker."
                    },
                    {
                      "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ",
                      "name": "silent",
                      "default": "false",
                      "type": "Boolean",
                      "desc": "whether or not to send output to parent's stdio."
                    }
                  ],
                  "name": "settings",
                  "type": "Object",
                  "optional": true
                }
              ]
            },
            {
              "params": [
                {
                  "name": "settings",
                  "optional": true
                }
              ]
            }
          ],
          "desc": "<p><code>setupMaster</code> is used to change the default &#39;fork&#39; behavior. The new settings\nare effective immediately and permanently, they cannot be changed later on.\n\n</p>\n<p>Example:\n\n</p>\n<pre><code>var cluster = require(&quot;cluster&quot;);\ncluster.setupMaster({\n  exec : &quot;worker.js&quot;,\n  args : [&quot;--use&quot;, &quot;https&quot;],\n  silent : true\n});\ncluster.fork();</code></pre>\n"
        },
        {
          "textRaw": "cluster.fork([env])",
          "type": "method",
          "name": "fork",
          "signatures": [
            {
              "return": {
                "textRaw": "return {Worker object} ",
                "name": "return",
                "type": "Worker object"
              },
              "params": [
                {
                  "textRaw": "`env` {Object} Key/value pairs to add to child process environment. ",
                  "name": "env",
                  "type": "Object",
                  "desc": "Key/value pairs to add to child process environment.",
                  "optional": true
                }
              ]
            },
            {
              "params": [
                {
                  "name": "env",
                  "optional": true
                }
              ]
            }
          ],
          "desc": "<p>Spawn a new worker process. This can only be called from the master process.\n\n</p>\n"
        },
        {
          "textRaw": "cluster.disconnect([callback])",
          "type": "method",
          "name": "disconnect",
          "signatures": [
            {
              "params": [
                {
                  "textRaw": "`callback` {Function} called when all workers are disconnected and handlers are closed ",
                  "name": "callback",
                  "type": "Function",
                  "desc": "called when all workers are disconnected and handlers are closed",
                  "optional": true
                }
              ]
            },
            {
              "params": [
                {
                  "name": "callback",
                  "optional": true
                }
              ]
            }
          ],
          "desc": "<p>When calling this method, all workers will commit a graceful suicide. When they are\ndisconnected all internal handlers will be closed, allowing the master process to\ndie graceful if no other event is waiting.\n\n</p>\n<p>The method takes an optional callback argument which will be called when finished.\n\n</p>\n"
        }
      ],
      "classes": [
        {
          "textRaw": "Class: Worker",
          "type": "class",
          "name": "Worker",
          "desc": "<p>A Worker 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>.\n\n</p>\n",
          "properties": [
            {
              "textRaw": "`id` {String} ",
              "name": "id",
              "desc": "<p>Each new worker is given its own unique id, this id is stored in the\n<code>id</code>.\n\n</p>\n<p>While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n</p>\n"
            },
            {
              "textRaw": "`process` {ChildProcess object} ",
              "name": "process",
              "desc": "<p>All workers are created using <code>child_process.fork()</code>, the returned object\nfrom this function is stored in process.\n\n</p>\n<p>See: <a href=\"child_process.html\">Child Process module</a>\n\n</p>\n"
            },
            {
              "textRaw": "`suicide` {Boolean} ",
              "name": "suicide",
              "desc": "<p>This property is a boolean. It is set when a worker dies after calling <code>.destroy()</code>\nor immediately after calling the <code>.disconnect()</code> method. Until then it is <code>undefined</code>.\n\n</p>\n"
            }
          ],
          "methods": [
            {
              "textRaw": "worker.send(message, [sendHandle])",
              "type": "method",
              "name": "send",
              "signatures": [
                {
                  "params": [
                    {
                      "textRaw": "`message` {Object} ",
                      "name": "message",
                      "type": "Object"
                    },
                    {
                      "textRaw": "`sendHandle` {Handle object} ",
                      "name": "sendHandle",
                      "type": "Handle object",
                      "optional": true
                    }
                  ]
                },
                {
                  "params": [
                    {
                      "name": "message"
                    },
                    {
                      "name": "sendHandle",
                      "optional": true
                    }
                  ]
                }
              ],
              "desc": "<p>This function is equal to the send methods provided by\n<code>child_process.fork()</code>.  In the master you should use this function to\nsend a message to a specific worker.  However in a worker you can also use\n<code>process.send(message)</code>, since this is the same function.\n\n</p>\n<p>This example will echo back all messages from the master:\n\n</p>\n<pre><code>if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send(&#39;hi there&#39;);\n\n} else if (cluster.isWorker) {\n  process.on(&#39;message&#39;, function(msg) {\n    process.send(msg);\n  });\n}</code></pre>\n"
            },
            {
              "textRaw": "worker.destroy()",
              "type": "method",
              "name": "destroy",
              "desc": "<p>This function will kill the worker, and inform the master to not spawn a\nnew worker.  The boolean <code>suicide</code> lets you distinguish between voluntary\nand accidental exit.\n\n</p>\n<pre><code>cluster.on(&#39;exit&#39;, function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log(&#39;Oh, it was just suicide\\&#39; – no need to worry&#39;).\n  }\n});\n\n// destroy worker\nworker.destroy();</code></pre>\n",
              "signatures": [
                {
                  "params": []
                }
              ]
            },
            {
              "textRaw": "worker.disconnect()",
              "type": "method",
              "name": "disconnect",
              "desc": "<p>When calling this function the worker will no longer accept new connections, but\nthey will be handled by any other listening worker. Existing connection will be\nallowed to exit as usual. When no more connections exist, the IPC channel to the worker\nwill close allowing it to die graceful. When the IPC channel is closed the <code>disconnect</code>\nevent will emit, this is then followed by the <code>exit</code> event, there is emitted when\nthe worker finally die.\n\n</p>\n<p>Because there might be long living connections, it is useful to implement a timeout.\nThis example ask the worker to disconnect and after 2 seconds it will destroy the\nserver. An alternative would be to execute <code>worker.destroy()</code> after 2 seconds, but\nthat would normally not allow the worker to do any cleanup if needed.\n\n</p>\n<pre><code>if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on(&#39;listening&#39;, function(address) {\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.send(&#39;force kill&#39;);\n    }, 2000);\n  });\n\n  worker.on(&#39;disconnect&#39;, function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require(&#39;net&#39;);\n  var server = net.createServer(function(socket) {\n    // connection never end\n  });\n\n  server.listen(8000);\n\n  server.on(&#39;close&#39;, function() {\n    // cleanup\n  });\n\n  process.on(&#39;message&#39;, function(msg) {\n    if (msg === &#39;force kill&#39;) {\n      server.destroy();\n    }\n  });\n}</code></pre>\n",
              "signatures": [
                {
                  "params": []
                }
              ]
            }
          ],
          "events": [
            {
              "textRaw": "Event: 'message'",
              "type": "event",
              "name": "message",
              "params": [],
              "desc": "<p>This event is the same as the one provided by <code>child_process.fork()</code>.\nIn the master you should use this event, however in a worker you can also use\n<code>process.on(&#39;message&#39;)</code>\n\n</p>\n<p>As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n</p>\n<pre><code>var cluster = require(&#39;cluster&#39;);\nvar http = require(&#39;http&#39;);\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log(&quot;numReqs =&quot;, numReqs);\n  }, 1000);\n\n  // Count requestes\n  function messageHandler(msg) {\n    if (msg.cmd &amp;&amp; msg.cmd == &#39;notifyRequest&#39;) {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  var numCPUs = require(&#39;os&#39;).cpus().length;\n  for (var i = 0; i &lt; numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on(&#39;message&#39;, messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end(&quot;hello world\\n&quot;);\n\n    // notify master about the request\n    process.send({ cmd: &#39;notifyRequest&#39; });\n  }).listen(8000);\n}</code></pre>\n"
            },
            {
              "textRaw": "Event: 'online'",
              "type": "event",
              "name": "online",
              "desc": "<p>Same as the <code>cluster.on(&#39;online&#39;)</code> event, but emits only when the state change\non the specified worker.\n\n</p>\n<pre><code>cluster.fork().on(&#39;online&#39;, function() {\n  // Worker is online\n};</code></pre>\n",
              "params": []
            },
            {
              "textRaw": "Event: 'listening'",
              "type": "event",
              "name": "listening",
              "params": [],
              "desc": "<p>Same as the <code>cluster.on(&#39;listening&#39;)</code> event, but emits only when the state change\non the specified worker.\n\n</p>\n<pre><code>cluster.fork().on(&#39;listening&#39;, function(address) {\n  // Worker is listening\n};</code></pre>\n"
            },
            {
              "textRaw": "Event: 'disconnect'",
              "type": "event",
              "name": "disconnect",
              "desc": "<p>Same as the <code>cluster.on(&#39;disconnect&#39;)</code> event, but emits only when the state change\non the specified worker.\n\n</p>\n<pre><code>cluster.fork().on(&#39;disconnect&#39;, function() {\n  // Worker has disconnected\n};</code></pre>\n",
              "params": []
            },
            {
              "textRaw": "Event: 'exit'",
              "type": "event",
              "name": "exit",
              "params": [],
              "desc": "<p>Emitted by the individual worker instance, when the underlying child process\nis terminated.  See <a href=\"child_process.html#child_process_event_exit\">child_process event: &#39;exit&#39;</a>.\n\n</p>\n<pre><code>var worker = cluster.fork();\nworker.on(&#39;exit&#39;, function(code, signal) {\n  if( signal ) {\n    console.log(&quot;worker was killed by signal: &quot;+signal);\n  } else if( code !== 0 ) {\n    console.log(&quot;worker exited with error code: &quot;+code);\n  } else {\n    console.log(&quot;worker success!&quot;);\n  }\n};</code></pre>\n"
            }
          ]
        }
      ],
      "type": "module",
      "displayName": "Cluster"
    }
  ]
}
