nodejs-mozilla/doc/api/cluster.json

761 lines
46 KiB
JSON
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"type": "module",
"source": "doc/api/cluster.md",
"modules": [
{
"textRaw": "Cluster",
"name": "cluster",
"introduced_in": "v0.10.0",
"stability": 2,
"stabilityText": "Stable",
"desc": "<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>",
"miscs": [
{
"textRaw": "How It Works",
"name": "How It Works",
"type": "misc",
"desc": "<p>The worker processes are spawned using the <a href=\"child_process.html#child_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>"
}
],
"classes": [
{
"textRaw": "Class: `Worker`",
"type": "class",
"name": "Worker",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"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>",
"events": [
{
"textRaw": "Event: `'disconnect'`",
"type": "event",
"name": "disconnect",
"meta": {
"added": [
"v0.7.7"
],
"changes": []
},
"params": [],
"desc": "<p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">cluster.fork().on('disconnect', () => {\n // Worker has disconnected\n});\n</code></pre>"
},
{
"textRaw": "Event: `'error'`",
"type": "event",
"name": "error",
"meta": {
"added": [
"v0.7.3"
],
"changes": []
},
"params": [],
"desc": "<p>This event is the same as the one provided by <a href=\"child_process.html#child_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>"
},
{
"textRaw": "Event: `'exit'`",
"type": "event",
"name": "exit",
"meta": {
"added": [
"v0.11.2"
],
"changes": []
},
"params": [
{
"textRaw": "`code` {number} The exit code, if it exited normally.",
"name": "code",
"type": "number",
"desc": "The exit code, if it exited normally."
},
{
"textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.",
"name": "signal",
"type": "string",
"desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed."
}
],
"desc": "<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-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>"
},
{
"textRaw": "Event: `'listening'`",
"type": "event",
"name": "listening",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`address` {Object}",
"name": "address",
"type": "Object"
}
],
"desc": "<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">cluster.fork().on('listening', (address) => {\n // Worker is listening\n});\n</code></pre>\n<p>It is not emitted in the worker.</p>"
},
{
"textRaw": "Event: `'message'`",
"type": "event",
"name": "message",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`message` {Object}",
"name": "message",
"type": "Object"
},
{
"textRaw": "`handle` {undefined|Object}",
"name": "handle",
"type": "undefined|Object"
}
],
"desc": "<p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p>\n<p>Within a worker, <code>process.on('message')</code> may also be used.</p>\n<p>See <a href=\"process.html#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>"
},
{
"textRaw": "Event: `'online'`",
"type": "event",
"name": "online",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [],
"desc": "<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p>\n<pre><code class=\"language-js\">cluster.fork().on('online', () => {\n // Worker is online\n});\n</code></pre>\n<p>It is not emitted in the worker.</p>"
}
],
"methods": [
{
"textRaw": "`worker.disconnect()`",
"type": "method",
"name": "disconnect",
"meta": {
"added": [
"v0.7.7"
],
"changes": [
{
"version": "v7.3.0",
"pr-url": "https://github.com/nodejs/node/pull/10019",
"description": "This method now returns a reference to `worker`."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {cluster.Worker} A reference to `worker`.",
"name": "return",
"type": "cluster.Worker",
"desc": "A reference to `worker`."
},
"params": []
}
],
"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>"
},
{
"textRaw": "`worker.isConnected()`",
"type": "method",
"name": "isConnected",
"meta": {
"added": [
"v0.11.14"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"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>"
},
{
"textRaw": "`worker.isDead()`",
"type": "method",
"name": "isDead",
"meta": {
"added": [
"v0.11.14"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "<p>This function returns <code>true</code> if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns <code>false</code>.</p>\n<pre><code class=\"language-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>"
},
{
"textRaw": "`worker.kill([signal='SIGTERM'])`",
"type": "method",
"name": "kill",
"meta": {
"added": [
"v0.9.12"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`signal` {string} Name of the kill signal to send to the worker process.",
"name": "signal",
"type": "string",
"desc": "Name of the kill signal to send to the worker process."
}
]
}
],
"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 backwards compatibility.</p>\n<p>In a worker, <code>process.kill()</code> exists, but it is not this function;\nit is <a href=\"process.html#process_process_kill_pid_signal\"><code>kill()</code></a>.</p>"
},
{
"textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`",
"type": "method",
"name": "send",
"meta": {
"added": [
"v0.7.0"
],
"changes": [
{
"version": "v4.0.0",
"pr-url": "https://github.com/nodejs/node/pull/2620",
"description": "The `callback` parameter is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
},
"params": [
{
"textRaw": "`message` {Object}",
"name": "message",
"type": "Object"
},
{
"textRaw": "`sendHandle` {Handle}",
"name": "sendHandle",
"type": "Handle"
},
{
"textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
"name": "options",
"type": "Object",
"desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
"options": [
{
"textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.",
"name": "keepOpen",
"type": "boolean",
"default": "`false`",
"desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process."
}
]
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function"
}
]
}
],
"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>"
}
],
"properties": [
{
"textRaw": "`exitedAfterDisconnect` {boolean}",
"type": "boolean",
"name": "exitedAfterDisconnect",
"meta": {
"added": [
"v6.0.0"
],
"changes": []
},
"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>"
},
{
"textRaw": "`id` {number}",
"type": "number",
"name": "id",
"meta": {
"added": [
"v0.8.0"
],
"changes": []
},
"desc": "<p>Each new worker is given its own unique id, this id is stored in the\n<code>id</code>.</p>\n<p>While a worker is alive, this is the key that indexes it in\n<code>cluster.workers</code>.</p>"
},
{
"textRaw": "`process` {ChildProcess}",
"type": "ChildProcess",
"name": "process",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"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>"
}
]
}
],
"events": [
{
"textRaw": "Event: `'disconnect'`",
"type": "event",
"name": "disconnect",
"meta": {
"added": [
"v0.7.9"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
}
],
"desc": "<p>Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\n<code>worker.disconnect()</code>).</p>\n<p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These\nevents can be used to detect if the process is stuck in a cleanup or if there\nare long-living connections.</p>\n<pre><code class=\"language-js\">cluster.on('disconnect', (worker) => {\n console.log(`The worker #${worker.id} has disconnected`);\n});\n</code></pre>"
},
{
"textRaw": "Event: `'exit'`",
"type": "event",
"name": "exit",
"meta": {
"added": [
"v0.7.9"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
},
{
"textRaw": "`code` {number} The exit code, if it exited normally.",
"name": "code",
"type": "number",
"desc": "The exit code, if it exited normally."
},
{
"textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.",
"name": "signal",
"type": "string",
"desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed."
}
],
"desc": "<p>When any of the workers die the cluster module will emit the <code>'exit'</code> event.</p>\n<p>This can be used to restart the worker by calling <a href=\"#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>"
},
{
"textRaw": "Event: `'fork'`",
"type": "event",
"name": "fork",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
}
],
"desc": "<p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event.\nThis can be used to log worker activity, and create a custom timeout.</p>\n<pre><code class=\"language-js\">const timeouts = [];\nfunction errorMsg() {\n console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n clearTimeout(timeouts[worker.id]);\n errorMsg();\n});\n</code></pre>"
},
{
"textRaw": "Event: `'listening'`",
"type": "event",
"name": "listening",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
},
{
"textRaw": "`address` {Object}",
"name": "address",
"type": "Object"
}
],
"desc": "<p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted\non the server a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the\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>"
},
{
"textRaw": "Event: `'message'`",
"type": "event",
"name": "message",
"meta": {
"added": [
"v2.5.0"
],
"changes": [
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/5361",
"description": "The `worker` parameter is passed now; see below for details."
}
]
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
},
{
"textRaw": "`message` {Object}",
"name": "message",
"type": "Object"
},
{
"textRaw": "`handle` {undefined|Object}",
"name": "handle",
"type": "undefined|Object"
}
],
"desc": "<p>Emitted when the cluster 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>"
},
{
"textRaw": "Event: `'online'`",
"type": "event",
"name": "online",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
}
],
"desc": "<p>After forking a new worker, the worker should respond with an online message.\nWhen the 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>"
},
{
"textRaw": "Event: `'setup'`",
"type": "event",
"name": "setup",
"meta": {
"added": [
"v0.7.1"
],
"changes": []
},
"params": [
{
"textRaw": "`settings` {Object}",
"name": "settings",
"type": "Object"
}
],
"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>"
}
],
"methods": [
{
"textRaw": "`cluster.disconnect([callback])`",
"type": "method",
"name": "disconnect",
"meta": {
"added": [
"v0.7.7"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function} Called when all workers are disconnected and handles are closed.",
"name": "callback",
"type": "Function",
"desc": "Called when all workers are disconnected and handles are closed."
}
]
}
],
"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>"
},
{
"textRaw": "`cluster.fork([env])`",
"type": "method",
"name": "fork",
"meta": {
"added": [
"v0.6.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {cluster.Worker}",
"name": "return",
"type": "cluster.Worker"
},
"params": [
{
"textRaw": "`env` {Object} Key/value pairs to add to worker process environment.",
"name": "env",
"type": "Object",
"desc": "Key/value pairs to add to worker process environment."
}
]
}
],
"desc": "<p>Spawn a new worker process.</p>\n<p>This can only be called from the master process.</p>"
},
{
"textRaw": "`cluster.setupMaster([settings])`",
"type": "method",
"name": "setupMaster",
"meta": {
"added": [
"v0.7.1"
],
"changes": [
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7838",
"description": "The `stdio` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`settings` {Object} See [`cluster.settings`][].",
"name": "settings",
"type": "Object",
"desc": "See [`cluster.settings`][]."
}
]
}
],
"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>"
}
],
"properties": [
{
"textRaw": "`isMaster` {boolean}",
"type": "boolean",
"name": "isMaster",
"meta": {
"added": [
"v0.8.1"
],
"changes": []
},
"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>"
},
{
"textRaw": "`isWorker` {boolean}",
"type": "boolean",
"name": "isWorker",
"meta": {
"added": [
"v0.6.0"
],
"changes": []
},
"desc": "<p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).</p>"
},
{
"textRaw": "`cluster.schedulingPolicy`",
"name": "schedulingPolicy",
"meta": {
"added": [
"v0.11.2"
],
"changes": []
},
"desc": "<p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or\n<code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a\nglobal setting and effectively frozen once either the first worker is spawned,\nor <a href=\"#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>"
},
{
"textRaw": "`settings` {Object}",
"type": "Object",
"name": "settings",
"meta": {
"added": [
"v0.7.1"
],
"changes": [
{
"version": "v12.16.0",
"pr-url": "https://github.com/nodejs/node/pull/30162",
"description": "The `serialization` option is supported now."
},
{
"version": "v9.5.0",
"pr-url": "https://github.com/nodejs/node/pull/18399",
"description": "The `cwd` option is supported now."
},
{
"version": "v9.4.0",
"pr-url": "https://github.com/nodejs/node/pull/17412",
"description": "The `windowsHide` option is supported now."
},
{
"version": "v8.2.0",
"pr-url": "https://github.com/nodejs/node/pull/14140",
"description": "The `inspectPort` option is supported now."
},
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7838",
"description": "The `stdio` option is supported now."
}
]
},
"options": [
{
"textRaw": "`execArgv` {string[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`.",
"name": "execArgv",
"type": "string[]",
"default": "`process.execArgv`",
"desc": "List of string arguments passed to the Node.js executable."
},
{
"textRaw": "`exec` {string} File path to worker file. **Default:** `process.argv[1]`.",
"name": "exec",
"type": "string",
"default": "`process.argv[1]`",
"desc": "File path to worker file."
},
{
"textRaw": "`args` {string[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`.",
"name": "args",
"type": "string[]",
"default": "`process.argv.slice(2)`",
"desc": "String arguments passed to worker."
},
{
"textRaw": "`cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process).",
"name": "cwd",
"type": "string",
"default": "`undefined` (inherits from parent process)",
"desc": "Current working directory of the worker process."
},
{
"textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced Serialization for `child_process`][] for more details. **Default:** `false`.",
"name": "serialization",
"type": "string",
"default": "`false`",
"desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced Serialization for `child_process`][] for more details."
},
{
"textRaw": "`silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false`.",
"name": "silent",
"type": "boolean",
"default": "`false`",
"desc": "Whether or not to send output to parent's stdio."
},
{
"textRaw": "`stdio` {Array} Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`.",
"name": "stdio",
"type": "Array",
"desc": "Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`."
},
{
"textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2).)",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process. (See setuid(2).)"
},
{
"textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2).)",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process. (See setgid(2).)"
},
{
"textRaw": "`inspectPort` {number|Function} Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`.",
"name": "inspectPort",
"type": "number|Function",
"desc": "Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`."
},
{
"textRaw": "`windowsHide` {boolean} Hide the forked processes console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the forked processes console window that would normally be created on Windows systems."
}
],
"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>"
},
{
"textRaw": "`worker` {Object}",
"type": "Object",
"name": "worker",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"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>"
},
{
"textRaw": "`workers` {Object}",
"type": "Object",
"name": "workers",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"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>"
}
],
"type": "module",
"displayName": "Cluster"
}
]
}