{
  "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(&apos;cluster&apos;);\nvar http = require(&apos;http&apos;);\nvar numCPUs = require(&apos;os&apos;).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(&apos;death&apos;, function(worker) {\n    console.log(&apos;worker &apos; + worker.pid + &apos; died&apos;);\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",
      "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 change 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": "`settings` {Object} ",
          "name": "settings",
          "options": [
            {
              "textRaw": "`exec` {String} file path to worker file.  Default: `__filename` ",
              "name": "exec",
              "type": "String",
              "desc": "file path to worker file.  Default: `__filename`"
            },
            {
              "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 change or set manually.\n\n</p>\n"
        },
        {
          "textRaw": "`workers` {Object} ",
          "name": "workers",
          "desc": "<p>In the cluster all living worker objects are stored in this object by there\n<code>uniqueID</code> as the key. This makes it easy to loop through all living workers.\n\n</p>\n<pre><code>// Go through all workers\nfunction eachWorker(callback) {\n  for (var uniqueID in cluster.workers) {\n    callback(cluster.workers[uniqueID]);\n  }\n}\neachWorker(function (worker) {\n  worker.send(&apos;big announcement to all workers&apos;);\n});</code></pre>\n<p>Should you wish to reference a worker over a communication channel, using\nthe worker&apos;s uniqueID is the easiest way to find the worker.\n\n</p>\n<pre><code>socket.on(&apos;data&apos;, function (uniqueID) {\n  var worker = cluster.workers[uniqueID];\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 &apos;fork&apos; event.\nThis can be used to log worker activity, and create you own timeout.\n\n</p>\n<pre><code>var timeouts = [];\nvar errorMsg = function () {\n  console.error(&quot;Something must be wrong with the connection ...&quot;);\n});\n\ncluster.on(&apos;fork&apos;, function (worker) {\n  timeouts[worker.uniqueID] = setTimeout(errorMsg, 2000);\n});\ncluster.on(&apos;listening&apos;, function (worker) {\n  clearTimeout(timeouts[worker.uniqueID]);\n});\ncluster.on(&apos;death&apos;, function (worker) {\n  clearTimeout(timeouts[worker.uniqueID]);\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 &apos;fork&apos; and &apos;online&apos; is that fork is emitted when the\nmaster tries to fork a worker, and &apos;online&apos; is emitted when the worker is\nbeing executed.\n\n</p>\n<pre><code>cluster.on(&apos;online&apos;, 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 &apos;listening&apos; event is automatically assigned\nto the server instance. When the server is listening a message is send to the master\nwhere the &apos;listening&apos; event is emitted.\n\n</p>\n<pre><code>cluster.on(&apos;listening&apos;, function (worker) {\n  console.log(&quot;We are now connected&quot;);\n});</code></pre>\n"
        },
        {
          "textRaw": "Event: 'death'",
          "type": "event",
          "name": "death",
          "params": [],
          "desc": "<p>When any of the workers die the cluster module will emit the &apos;death&apos; event.\nThis can be used to restart the worker by calling <code>fork()</code> again.\n\n</p>\n<pre><code>cluster.on(&apos;death&apos;, function(worker) {\n  console.log(&apos;worker &apos; + worker.pid + &apos; died. restart...&apos;);\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"
        },
        {
          "textRaw": "Event: 'death'",
          "type": "event",
          "name": "death",
          "params": [],
          "desc": "<p>Same as the <code>cluster.on(&apos;death&apos;)</code> event, but emits only when the state change\non the specified worker.\n\n</p>\n<pre><code>cluster.fork().on(&apos;death&apos;, function (worker) {\n  // Worker has died\n};</code></pre>\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>The <code>setupMaster</code> is used to change the default &apos;fork&apos; behavior. It takes\none option object argument.\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.autoFork();</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"
        }
      ],
      "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": "`uniqueID` {String} ",
              "name": "uniqueID",
              "desc": "<p>Each new worker is given its own unique id, this id is stored in the\n<code>uniqueID</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, until then it is\n<code>undefined</code>.  It is true if the worker was killed using the <code>.destroy()</code>\nmethod, and false otherwise.\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(&apos;hi there&apos;);\n\n} else if (cluster.isWorker) {\n  process.on(&apos;message&apos;, 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.  To know the difference between suicide and accidentally death\na suicide boolean is set to true.\n\n</p>\n<pre><code>cluster.on(&apos;death&apos;, function (worker) {\n  if (worker.suicide === true) {\n    console.log(&apos;Oh, it was just suicide\\&apos; – no need to worry&apos;).\n  }\n});\n\n// destroy worker\nworker.destroy();</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(&apos;message&apos;)</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(&apos;cluster&apos;);\nvar http = require(&apos;http&apos;);\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  var messageHandler = function (msg) {\n    if (msg.cmd &amp;&amp; msg.cmd == &apos;notifyRequest&apos;) {\n      numReqs += 1;\n    }\n  };\n\n  // Start workers and listen for messages containing notifyRequest\n  cluster.autoFork();\n  Object.keys(cluster.workers).forEach(function (uniqueID) {\n    cluster.workers[uniqueID].on(&apos;message&apos;, 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: &apos;notifyRequest&apos; });\n  }).listen(8000);\n}</code></pre>\n"
            },
            {
              "textRaw": "Event: 'online'",
              "type": "event",
              "name": "online",
              "params": [],
              "desc": "<p>Same as the <code>cluster.on(&apos;online&apos;)</code> event, but emits only when the state change\non the specified worker.\n\n</p>\n<pre><code>cluster.fork().on(&apos;online&apos;, function (worker) {\n  // Worker is online\n};</code></pre>\n"
            },
            {
              "textRaw": "Event: 'listening'",
              "type": "event",
              "name": "listening",
              "params": [],
              "desc": "<p>Same as the <code>cluster.on(&apos;listening&apos;)</code> event, but emits only when the state change\non the specified worker.\n\n</p>\n<pre><code>cluster.fork().on(&apos;listening&apos;, function (worker) {\n  // Worker is listening\n};</code></pre>\n"
            }
          ]
        }
      ],
      "type": "module",
      "displayName": "Cluster"
    }
  ]
}
