1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width"> 6 <meta name="nodejs.org:node-version" content="v14.20.1"> 7 <title>Cluster | Node.js v14.20.1 Documentation</title> 8 <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> 9 <link rel="stylesheet" href="assets/style.css"> 10 <link rel="stylesheet" href="assets/hljs.css"> 11 <link rel="canonical" href="https://nodejs.org/api/cluster.html"> 12</head> 13<body class="alt apidoc" id="api-section-cluster"> 14 <div id="content" class="clearfix"> 15 <div id="column2" class="interior"> 16 <div id="intro" class="interior"> 17 <a href="/" title="Go back to the home page"> 18 Node.js 19 </a> 20 </div> 21 <ul> 22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 24</ul> 25<hr class="line"> 26<ul> 27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 30<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 34<li><a href="cluster.html" class="nav-cluster active">Cluster</a></li> 35<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 36<li><a href="console.html" class="nav-console">Console</a></li> 37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 42<li><a href="dns.html" class="nav-dns">DNS</a></li> 43<li><a href="domain.html" class="nav-domain">Domain</a></li> 44<li><a href="errors.html" class="nav-errors">Errors</a></li> 45<li><a href="events.html" class="nav-events">Events</a></li> 46<li><a href="fs.html" class="nav-fs">File system</a></li> 47<li><a href="globals.html" class="nav-globals">Globals</a></li> 48<li><a href="http.html" class="nav-http">HTTP</a></li> 49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 50<li><a href="https.html" class="nav-https">HTTPS</a></li> 51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 52<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> 56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 57<li><a href="net.html" class="nav-net">Net</a></li> 58<li><a href="os.html" class="nav-os">OS</a></li> 59<li><a href="path.html" class="nav-path">Path</a></li> 60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 61<li><a href="policy.html" class="nav-policy">Policies</a></li> 62<li><a href="process.html" class="nav-process">Process</a></li> 63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 65<li><a href="readline.html" class="nav-readline">Readline</a></li> 66<li><a href="repl.html" class="nav-repl">REPL</a></li> 67<li><a href="report.html" class="nav-report">Report</a></li> 68<li><a href="stream.html" class="nav-stream">Stream</a></li> 69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 70<li><a href="timers.html" class="nav-timers">Timers</a></li> 71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 73<li><a href="tty.html" class="nav-tty">TTY</a></li> 74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 75<li><a href="url.html" class="nav-url">URL</a></li> 76<li><a href="util.html" class="nav-util">Utilities</a></li> 77<li><a href="v8.html" class="nav-v8">V8</a></li> 78<li><a href="vm.html" class="nav-vm">VM</a></li> 79<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 82</ul> 83<hr class="line"> 84<ul> 85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 86</ul> 87 </div> 88 89 <div id="column1" data-id="cluster" class="interior"> 90 <header> 91 <div class="header-container"> 92 <h1>Node.js v14.20.1 documentation</h1> 93 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 94 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 95 <path fill="none" d="M0 0h24v24H0z" /> 96 <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/> 97 <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/> 98 </svg> 99 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 100 <path d="M0 0h24v24H0z" fill="none" /> 101 <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> 102 </svg> 103 </button> 104 </div> 105 <div id="gtoc"> 106 <ul> 107 <li> 108 <a href="index.html">Index</a> 109 </li> 110 <li> 111 <a href="all.html">View on single page</a> 112 </li> 113 <li> 114 <a href="cluster.json">View as JSON</a> 115 </li> 116 117 <li class="version-picker"> 118 <a href="#">View another version <span>▼</span></a> 119 <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v18.x/api/cluster.html">18.x</a></li> 120<li><a href="https://nodejs.org/docs/latest-v17.x/api/cluster.html">17.x</a></li> 121<li><a href="https://nodejs.org/docs/latest-v16.x/api/cluster.html">16.x <b>LTS</b></a></li> 122<li><a href="https://nodejs.org/docs/latest-v15.x/api/cluster.html">15.x</a></li> 123<li><a href="https://nodejs.org/docs/latest-v14.x/api/cluster.html">14.x <b>LTS</b></a></li> 124<li><a href="https://nodejs.org/docs/latest-v13.x/api/cluster.html">13.x</a></li> 125<li><a href="https://nodejs.org/docs/latest-v12.x/api/cluster.html">12.x <b>LTS</b></a></li> 126<li><a href="https://nodejs.org/docs/latest-v11.x/api/cluster.html">11.x</a></li> 127<li><a href="https://nodejs.org/docs/latest-v10.x/api/cluster.html">10.x</a></li> 128<li><a href="https://nodejs.org/docs/latest-v9.x/api/cluster.html">9.x</a></li> 129<li><a href="https://nodejs.org/docs/latest-v8.x/api/cluster.html">8.x</a></li> 130<li><a href="https://nodejs.org/docs/latest-v7.x/api/cluster.html">7.x</a></li> 131<li><a href="https://nodejs.org/docs/latest-v6.x/api/cluster.html">6.x</a></li> 132<li><a href="https://nodejs.org/docs/latest-v5.x/api/cluster.html">5.x</a></li> 133<li><a href="https://nodejs.org/docs/latest-v4.x/api/cluster.html">4.x</a></li> 134<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/cluster.html">0.12.x</a></li> 135<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/cluster.html">0.10.x</a></li></ol> 136 </li> 137 138 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/cluster.md">Edit on GitHub</a></li> 139 </ul> 140 </div> 141 <hr> 142 </header> 143 144 <details id="toc" open><summary>Table of contents</summary><ul> 145<li><span class="stability_2"><a href="#cluster_cluster">Cluster</a></span> 146<ul> 147<li><a href="#cluster_how_it_works">How it works</a></li> 148<li><a href="#cluster_class_worker">Class: <code>Worker</code></a> 149<ul> 150<li><a href="#cluster_event_disconnect">Event: <code>'disconnect'</code></a></li> 151<li><a href="#cluster_event_error">Event: <code>'error'</code></a></li> 152<li><a href="#cluster_event_exit">Event: <code>'exit'</code></a></li> 153<li><a href="#cluster_event_listening">Event: <code>'listening'</code></a></li> 154<li><a href="#cluster_event_message">Event: <code>'message'</code></a></li> 155<li><a href="#cluster_event_online">Event: <code>'online'</code></a></li> 156<li><a href="#cluster_worker_disconnect"><code>worker.disconnect()</code></a></li> 157<li><a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a></li> 158<li><a href="#cluster_worker_id"><code>worker.id</code></a></li> 159<li><a href="#cluster_worker_isconnected"><code>worker.isConnected()</code></a></li> 160<li><a href="#cluster_worker_isdead"><code>worker.isDead()</code></a></li> 161<li><a href="#cluster_worker_kill_signal"><code>worker.kill([signal])</code></a></li> 162<li><a href="#cluster_worker_process"><code>worker.process</code></a></li> 163<li><a href="#cluster_worker_send_message_sendhandle_options_callback"><code>worker.send(message[, sendHandle[, options]][, callback])</code></a></li> 164</ul> 165</li> 166<li><a href="#cluster_event_disconnect_1">Event: <code>'disconnect'</code></a></li> 167<li><a href="#cluster_event_exit_1">Event: <code>'exit'</code></a></li> 168<li><a href="#cluster_event_fork">Event: <code>'fork'</code></a></li> 169<li><a href="#cluster_event_listening_1">Event: <code>'listening'</code></a></li> 170<li><a href="#cluster_event_message_1">Event: <code>'message'</code></a></li> 171<li><a href="#cluster_event_online_1">Event: <code>'online'</code></a></li> 172<li><a href="#cluster_event_setup">Event: <code>'setup'</code></a></li> 173<li><a href="#cluster_cluster_disconnect_callback"><code>cluster.disconnect([callback])</code></a></li> 174<li><a href="#cluster_cluster_fork_env"><code>cluster.fork([env])</code></a></li> 175<li><a href="#cluster_cluster_ismaster"><code>cluster.isMaster</code></a></li> 176<li><a href="#cluster_cluster_isworker"><code>cluster.isWorker</code></a></li> 177<li><a href="#cluster_cluster_schedulingpolicy"><code>cluster.schedulingPolicy</code></a></li> 178<li><a href="#cluster_cluster_settings"><code>cluster.settings</code></a></li> 179<li><a href="#cluster_cluster_setupmaster_settings"><code>cluster.setupMaster([settings])</code></a></li> 180<li><a href="#cluster_cluster_worker"><code>cluster.worker</code></a></li> 181<li><a href="#cluster_cluster_workers"><code>cluster.workers</code></a></li> 182</ul> 183</li> 184</ul></details> 185 186 <div id="apicontent"> 187 <h2>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h2> 188 189<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> 190<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v14.20.1/lib/cluster.js">lib/cluster.js</a></p> 191<p>A single instance of Node.js runs in a single thread. To take advantage of 192multi-core systems, the user will sometimes want to launch a cluster of Node.js 193processes to handle the load.</p> 194<p>The cluster module allows easy creation of child processes that all share 195server ports.</p> 196<pre><code class="language-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>); 197<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); 198<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>).<span class="hljs-title function_">cpus</span>().<span class="hljs-property">length</span>; 199 200<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) { 201 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Master <span class="hljs-subst">${process.pid}</span> is running`</span>); 202 203 <span class="hljs-comment">// Fork workers.</span> 204 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) { 205 cluster.<span class="hljs-title function_">fork</span>(); 206 } 207 208 cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> { 209 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>); 210 }); 211} <span class="hljs-keyword">else</span> { 212 <span class="hljs-comment">// Workers can share any TCP connection</span> 213 <span class="hljs-comment">// In this case it is an HTTP server</span> 214 http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { 215 res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>); 216 res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>); 217 }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>); 218 219 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>); 220}</code></pre> 221<p>Running Node.js will now share port 8000 between the workers:</p> 222<pre><code class="language-console"><span class="hljs-meta">$ </span><span class="language-bash">node server.js</span> 223Master 3596 is running 224Worker 4324 started 225Worker 4520 started 226Worker 6056 started 227Worker 5644 started</code></pre> 228<p>On Windows, it is not yet possible to set up a named pipe server in a worker.</p> 229<section><h3>How it works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h3> 230 231<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, 232so that they can communicate with the parent via IPC and pass server 233handles back and forth.</p> 234<p>The cluster module supports two methods of distributing incoming 235connections.</p> 236<p>The first one (and the default one on all platforms except Windows), 237is the round-robin approach, where the master process listens on a 238port, accepts new connections and distributes them across the workers 239in a round-robin fashion, with some built-in smarts to avoid 240overloading a worker process.</p> 241<p>The second approach is where the master process creates the listen 242socket and sends it to interested workers. The workers then accept 243incoming connections directly.</p> 244<p>The second approach should, in theory, give the best performance. 245In practice however, distribution tends to be very unbalanced due 246to operating system scheduler vagaries. Loads have been observed 247where over 70% of all connections ended up in just two processes, 248out of a total of eight.</p> 249<p>Because <code>server.listen()</code> hands off most of the work to the master 250process, there are three cases where the behavior between a normal 251Node.js process and a cluster worker differs:</p> 252<ol> 253<li><code>server.listen({fd: 7})</code> Because the message is passed to the master, 254file descriptor 7 <strong>in the parent</strong> will be listened on, and the 255handle passed to the worker, rather than listening to the worker's 256idea of what the number 7 file descriptor references.</li> 257<li><code>server.listen(handle)</code> Listening on handles explicitly will cause 258the worker to use the supplied handle, rather than talk to the master 259process.</li> 260<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a 261random port. However, in a cluster, each worker will receive the 262same "random" port each time they do <code>listen(0)</code>. In essence, the 263port is random the first time, but predictable thereafter. To listen 264on a unique port, generate a port number based on the cluster worker ID.</li> 265</ol> 266<p>Node.js does not provide routing logic. It is, therefore important to design an 267application such that it does not rely too heavily on in-memory data objects for 268things like sessions and login.</p> 269<p>Because workers are all separate processes, they can be killed or 270re-spawned depending on a program's needs, without affecting other 271workers. As long as there are some workers still alive, the server will 272continue to accept connections. If no workers are alive, existing connections 273will be dropped and new connections will be refused. Node.js does not 274automatically manage the number of workers, however. It is the application's 275responsibility to manage the worker pool based on its own needs.</p> 276<p>Although a primary use case for the <code>cluster</code> module is networking, it can 277also be used for other use cases requiring worker processes.</p> 278</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#cluster_class_worker" id="cluster_class_worker">#</a></span></h3> 279<div class="api_metadata"> 280<span>Added in: v0.7.0</span> 281</div> 282<ul> 283<li>Extends: <a href="events.html#events_class_eventemitter" class="type"><EventEmitter></a></li> 284</ul> 285<p>A <code>Worker</code> object contains all public information and method about a worker. 286In the master it can be obtained using <code>cluster.workers</code>. In a worker 287it can be obtained using <code>cluster.worker</code>.</p> 288<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h4> 289<div class="api_metadata"> 290<span>Added in: v0.7.7</span> 291</div> 292<p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p> 293<pre><code class="language-js">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> { 294 <span class="hljs-comment">// Worker has disconnected</span> 295});</code></pre> 296<h4>Event: <code>'error'</code><span><a class="mark" href="#cluster_event_error" id="cluster_event_error">#</a></span></h4> 297<div class="api_metadata"> 298<span>Added in: v0.7.3</span> 299</div> 300<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> 301<p>Within a worker, <code>process.on('error')</code> may also be used.</p> 302<h4>Event: <code>'exit'</code><span><a class="mark" href="#cluster_event_exit" id="cluster_event_exit">#</a></span></h4> 303<div class="api_metadata"> 304<span>Added in: v0.11.2</span> 305</div> 306<ul> 307<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code, if it exited normally.</li> 308<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused 309the process to be killed.</li> 310</ul> 311<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p> 312<pre><code class="language-js"><span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>(); 313worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> { 314 <span class="hljs-keyword">if</span> (signal) { 315 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker was killed by signal: <span class="hljs-subst">${signal}</span>`</span>); 316 } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) { 317 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker exited with error code: <span class="hljs-subst">${code}</span>`</span>); 318 } <span class="hljs-keyword">else</span> { 319 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>); 320 } 321});</code></pre> 322<h4>Event: <code>'listening'</code><span><a class="mark" href="#cluster_event_listening" id="cluster_event_listening">#</a></span></h4> 323<div class="api_metadata"> 324<span>Added in: v0.7.0</span> 325</div> 326<ul> 327<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 328</ul> 329<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p> 330<pre><code class="language-js">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> { 331 <span class="hljs-comment">// Worker is listening</span> 332});</code></pre> 333<p>It is not emitted in the worker.</p> 334<h4>Event: <code>'message'</code><span><a class="mark" href="#cluster_event_message" id="cluster_event_message">#</a></span></h4> 335<div class="api_metadata"> 336<span>Added in: v0.7.0</span> 337</div> 338<ul> 339<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 340<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 341</ul> 342<p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p> 343<p>Within a worker, <code>process.on('message')</code> may also be used.</p> 344<p>See <a href="process.html#process_event_message"><code>process</code> event: <code>'message'</code></a>.</p> 345<p>Here is an example using the message system. It keeps a count in the master 346process of the number of HTTP requests received by the workers:</p> 347<pre><code class="language-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>); 348<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); 349 350<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) { 351 352 <span class="hljs-comment">// Keep track of http requests</span> 353 <span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>; 354 <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> { 355 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`numReqs = <span class="hljs-subst">${numReqs}</span>`</span>); 356 }, <span class="hljs-number">1000</span>); 357 358 <span class="hljs-comment">// Count requests</span> 359 <span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) { 360 <span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> && msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) { 361 numReqs += <span class="hljs-number">1</span>; 362 } 363 } 364 365 <span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span> 366 <span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>).<span class="hljs-title function_">cpus</span>().<span class="hljs-property">length</span>; 367 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) { 368 cluster.<span class="hljs-title function_">fork</span>(); 369 } 370 371 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> id <span class="hljs-keyword">in</span> cluster.<span class="hljs-property">workers</span>) { 372 cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler); 373 } 374 375} <span class="hljs-keyword">else</span> { 376 377 <span class="hljs-comment">// Worker processes have a http server.</span> 378 http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { 379 res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>); 380 res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>); 381 382 <span class="hljs-comment">// Notify master about the request</span> 383 process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> }); 384 }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>); 385}</code></pre> 386<h4>Event: <code>'online'</code><span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h4> 387<div class="api_metadata"> 388<span>Added in: v0.7.0</span> 389</div> 390<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p> 391<pre><code class="language-js">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'online'</span>, <span class="hljs-function">() =></span> { 392 <span class="hljs-comment">// Worker is online</span> 393});</code></pre> 394<p>It is not emitted in the worker.</p> 395<h4><code>worker.disconnect()</code><span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h4> 396<div class="api_metadata"> 397<details class="changelog"><summary>History</summary> 398<table> 399<tbody><tr><th>Version</th><th>Changes</th></tr> 400<tr><td>v7.3.0</td> 401<td><p>This method now returns a reference to <code>worker</code>.</p></td></tr> 402<tr><td>v0.7.7</td> 403<td><p><span>Added in: v0.7.7</span></p></td></tr> 404</tbody></table> 405</details> 406</div> 407<ul> 408<li>Returns: <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a> A reference to <code>worker</code>.</li> 409</ul> 410<p>In a worker, this function will close all servers, wait for the <code>'close'</code> event 411on those servers, and then disconnect the IPC channel.</p> 412<p>In the master, an internal message is sent to the worker causing it to call 413<code>.disconnect()</code> on itself.</p> 414<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p> 415<p>After a server is closed, it will no longer accept new connections, 416but connections may be accepted by any other listening worker. Existing 417connections will be allowed to close as usual. When no more connections exist, 418see <a href="net.html#net_event_close"><code>server.close()</code></a>, the IPC channel to the worker will close allowing it 419to die gracefully.</p> 420<p>The above applies <em>only</em> to server connections, client connections are not 421automatically closed by workers, and disconnect does not wait for them to close 422before exiting.</p> 423<p>In a worker, <code>process.disconnect</code> exists, but it is not this function; 424it is <a href="child_process.html#child_process_subprocess_disconnect"><code>disconnect()</code></a>.</p> 425<p>Because long living server connections may block workers from disconnecting, it 426may be useful to send a message, so application specific actions may be taken to 427close them. It also may be useful to implement a timeout, killing a worker if 428the <code>'disconnect'</code> event has not been emitted after some time.</p> 429<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) { 430 <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>(); 431 <span class="hljs-keyword">let</span> timeout; 432 433 worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> { 434 worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'shutdown'</span>); 435 worker.<span class="hljs-title function_">disconnect</span>(); 436 timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 437 worker.<span class="hljs-title function_">kill</span>(); 438 }, <span class="hljs-number">2000</span>); 439 }); 440 441 worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> { 442 <span class="hljs-built_in">clearTimeout</span>(timeout); 443 }); 444 445} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) { 446 <span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'net'</span>); 447 <span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 448 <span class="hljs-comment">// Connections never end</span> 449 }); 450 451 server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>); 452 453 process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { 454 <span class="hljs-keyword">if</span> (msg === <span class="hljs-string">'shutdown'</span>) { 455 <span class="hljs-comment">// Initiate graceful close of any connections to server</span> 456 } 457 }); 458}</code></pre> 459<h4><code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#cluster_worker_exitedafterdisconnect" id="cluster_worker_exitedafterdisconnect">#</a></span></h4> 460<div class="api_metadata"> 461<span>Added in: v6.0.0</span> 462</div> 463<ul> 464<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 465</ul> 466<p>This property is <code>true</code> if the worker exited due to <code>.kill()</code> or 467<code>.disconnect()</code>. If the worker exited any other way, it is <code>false</code>. If the 468worker has not exited, it is <code>undefined</code>.</p> 469<p>The boolean <a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between 470voluntary and accidental exit, the master may choose not to respawn a worker 471based on this value.</p> 472<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> { 473 <span class="hljs-keyword">if</span> (worker.<span class="hljs-property">exitedAfterDisconnect</span> === <span class="hljs-literal">true</span>) { 474 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Oh, it was just voluntary – no need to worry'</span>); 475 } 476}); 477 478<span class="hljs-comment">// kill worker</span> 479worker.<span class="hljs-title function_">kill</span>();</code></pre> 480<h4><code>worker.id</code><span><a class="mark" href="#cluster_worker_id" id="cluster_worker_id">#</a></span></h4> 481<div class="api_metadata"> 482<span>Added in: v0.8.0</span> 483</div> 484<ul> 485<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 486</ul> 487<p>Each new worker is given its own unique id, this id is stored in the 488<code>id</code>.</p> 489<p>While a worker is alive, this is the key that indexes it in 490<code>cluster.workers</code>.</p> 491<h4><code>worker.isConnected()</code><span><a class="mark" href="#cluster_worker_isconnected" id="cluster_worker_isconnected">#</a></span></h4> 492<div class="api_metadata"> 493<span>Added in: v0.11.14</span> 494</div> 495<p>This function returns <code>true</code> if the worker is connected to its master via its 496IPC channel, <code>false</code> otherwise. A worker is connected to its master after it 497has been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p> 498<h4><code>worker.isDead()</code><span><a class="mark" href="#cluster_worker_isdead" id="cluster_worker_isdead">#</a></span></h4> 499<div class="api_metadata"> 500<span>Added in: v0.11.14</span> 501</div> 502<p>This function returns <code>true</code> if the worker's process has terminated (either 503because of exiting or being signaled). Otherwise, it returns <code>false</code>.</p> 504<pre><code class="language-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>); 505<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); 506<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>).<span class="hljs-title function_">cpus</span>().<span class="hljs-property">length</span>; 507 508<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) { 509 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Master <span class="hljs-subst">${process.pid}</span> is running`</span>); 510 511 <span class="hljs-comment">// Fork workers.</span> 512 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) { 513 cluster.<span class="hljs-title function_">fork</span>(); 514 } 515 516 cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> { 517 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>()); 518 }); 519 520 cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> { 521 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>()); 522 }); 523} <span class="hljs-keyword">else</span> { 524 <span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span> 525 http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { 526 res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>); 527 res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>); 528 process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>); 529 }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>); 530}</code></pre> 531<h4><code>worker.kill([signal])</code><span><a class="mark" href="#cluster_worker_kill_signal" id="cluster_worker_kill_signal">#</a></span></h4> 532<div class="api_metadata"> 533<span>Added in: v0.9.12</span> 534</div> 535<ul> 536<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the kill signal to send to the worker 537process. <strong>Default</strong>: <code>'SIGTERM'</code></li> 538</ul> 539<p>This function will kill the worker. In the master, it does this by disconnecting 540the <code>worker.process</code>, and once disconnected, killing with <code>signal</code>. In the 541worker, it does it by disconnecting the channel, and then exiting with code <code>0</code>.</p> 542<p>Because <code>kill()</code> attempts to gracefully disconnect the worker process, it is 543susceptible to waiting indefinitely for the disconnect to complete. For example, 544if the worker enters an infinite loop, a graceful disconnect will never occur. 545If the graceful disconnect behavior is not needed, use <code>worker.process.kill()</code>.</p> 546<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p> 547<p>This method is aliased as <code>worker.destroy()</code> for backward compatibility.</p> 548<p>In a worker, <code>process.kill()</code> exists, but it is not this function; 549it is <a href="process.html#process_process_kill_pid_signal"><code>kill()</code></a>.</p> 550<h4><code>worker.process</code><span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h4> 551<div class="api_metadata"> 552<span>Added in: v0.7.0</span> 553</div> 554<ul> 555<li><a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li> 556</ul> 557<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 558from this function is stored as <code>.process</code>. In a worker, the global <code>process</code> 559is stored.</p> 560<p>See: <a href="child_process.html#child_process_child_process_fork_modulepath_args_options">Child Process module</a>.</p> 561<p>Workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs 562on <code>process</code> and <code>.exitedAfterDisconnect</code> is not <code>true</code>. This protects against 563accidental disconnection.</p> 564<h4><code>worker.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#cluster_worker_send_message_sendhandle_options_callback" id="cluster_worker_send_message_sendhandle_options_callback">#</a></span></h4> 565<div class="api_metadata"> 566<details class="changelog"><summary>History</summary> 567<table> 568<tbody><tr><th>Version</th><th>Changes</th></tr> 569<tr><td>v4.0.0</td> 570<td><p>The <code>callback</code> parameter is supported now.</p></td></tr> 571<tr><td>v0.7.0</td> 572<td><p><span>Added in: v0.7.0</span></p></td></tr> 573</tbody></table> 574</details> 575</div> 576<ul> 577<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 578<li><code>sendHandle</code> <a href="net.html#net_server_listen_handle_backlog_callback" class="type"><Handle></a></li> 579<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <code>options</code> argument, if present, is an object used to 580parameterize the sending of certain types of handles. <code>options</code> supports 581the following properties: 582<ul> 583<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A value that can be used when passing instances of 584<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process. 585<strong>Default:</strong> <code>false</code>.</li> 586</ul> 587</li> 588<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> 589<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 590</ul> 591<p>Send a message to a worker or master, optionally with a handle.</p> 592<p>In the master this sends a message to a specific worker. It is identical to 593<a href="child_process.html#child_process_subprocess_send_message_sendhandle_options_callback"><code>ChildProcess.send()</code></a>.</p> 594<p>In a worker this sends a message to the master. It is identical to 595<code>process.send()</code>.</p> 596<p>This example will echo back all messages from the master:</p> 597<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) { 598 <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>(); 599 worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'hi there'</span>); 600 601} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) { 602 process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { 603 process.<span class="hljs-title function_">send</span>(msg); 604 }); 605}</code></pre> 606</section><section><h3>Event: <code>'disconnect'</code><span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h3> 607<div class="api_metadata"> 608<span>Added in: v0.7.9</span> 609</div> 610<ul> 611<li><code>worker</code> <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 612</ul> 613<p>Emitted after the worker IPC channel has disconnected. This can occur when a 614worker exits gracefully, is killed, or is disconnected manually (such as with 615<code>worker.disconnect()</code>).</p> 616<p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These 617events can be used to detect if the process is stuck in a cleanup or if there 618are long-living connections.</p> 619<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> { 620 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The worker #<span class="hljs-subst">${worker.id}</span> has disconnected`</span>); 621});</code></pre> 622</section><section><h3>Event: <code>'exit'</code><span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h3> 623<div class="api_metadata"> 624<span>Added in: v0.7.9</span> 625</div> 626<ul> 627<li><code>worker</code> <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 628<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code, if it exited normally.</li> 629<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused 630the process to be killed.</li> 631</ul> 632<p>When any of the workers die the cluster module will emit the <code>'exit'</code> event.</p> 633<p>This can be used to restart the worker by calling <a href="#cluster_cluster_fork_env"><code>.fork()</code></a> again.</p> 634<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> { 635 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker %d died (%s). restarting...'</span>, 636 worker.<span class="hljs-property">process</span>.<span class="hljs-property">pid</span>, signal || code); 637 cluster.<span class="hljs-title function_">fork</span>(); 638});</code></pre> 639<p>See <a href="child_process.html#child_process_event_exit"><code>child_process</code> event: <code>'exit'</code></a>.</p> 640</section><section><h3>Event: <code>'fork'</code><span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h3> 641<div class="api_metadata"> 642<span>Added in: v0.7.0</span> 643</div> 644<ul> 645<li><code>worker</code> <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 646</ul> 647<p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event. 648This can be used to log worker activity, and create a custom timeout.</p> 649<pre><code class="language-js"><span class="hljs-keyword">const</span> timeouts = []; 650<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorMsg</span>(<span class="hljs-params"></span>) { 651 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Something must be wrong with the connection ...'</span>); 652} 653 654cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> { 655 timeouts[worker.<span class="hljs-property">id</span>] = <span class="hljs-built_in">setTimeout</span>(errorMsg, <span class="hljs-number">2000</span>); 656}); 657cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">worker, address</span>) =></span> { 658 <span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]); 659}); 660cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> { 661 <span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]); 662 <span class="hljs-title function_">errorMsg</span>(); 663});</code></pre> 664</section><section><h3>Event: <code>'listening'</code><span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h3> 665<div class="api_metadata"> 666<span>Added in: v0.7.0</span> 667</div> 668<ul> 669<li><code>worker</code> <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 670<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 671</ul> 672<p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted 673on the server a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the 674master.</p> 675<p>The event handler is executed with two arguments, the <code>worker</code> contains the 676worker object and the <code>address</code> object contains the following connection 677properties: <code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the 678worker is listening on more than one address.</p> 679<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">worker, address</span>) =></span> { 680 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>( 681 <span class="hljs-string">`A worker is now connected to <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>); 682});</code></pre> 683<p>The <code>addressType</code> is one of:</p> 684<ul> 685<li><code>4</code> (TCPv4)</li> 686<li><code>6</code> (TCPv6)</li> 687<li><code>-1</code> (Unix domain socket)</li> 688<li><code>'udp4'</code> or <code>'udp6'</code> (UDP v4 or v6)</li> 689</ul> 690</section><section><h3>Event: <code>'message'</code><span><a class="mark" href="#cluster_event_message_1" id="cluster_event_message_1">#</a></span></h3> 691<div class="api_metadata"> 692<details class="changelog"><summary>History</summary> 693<table> 694<tbody><tr><th>Version</th><th>Changes</th></tr> 695<tr><td>v6.0.0</td> 696<td><p>The <code>worker</code> parameter is passed now; see below for details.</p></td></tr> 697<tr><td>v2.5.0</td> 698<td><p><span>Added in: v2.5.0</span></p></td></tr> 699</tbody></table> 700</details> 701</div> 702<ul> 703<li><code>worker</code> <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 704<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 705<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 706</ul> 707<p>Emitted when the cluster master receives a message from any worker.</p> 708<p>See <a href="child_process.html#child_process_event_message"><code>child_process</code> event: <code>'message'</code></a>.</p> 709</section><section><h3>Event: <code>'online'</code><span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h3> 710<div class="api_metadata"> 711<span>Added in: v0.7.0</span> 712</div> 713<ul> 714<li><code>worker</code> <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 715</ul> 716<p>After forking a new worker, the worker should respond with an online message. 717When the master receives an online message it will emit this event. 718The difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the 719master forks a worker, and <code>'online'</code> is emitted when the worker is running.</p> 720<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'online'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> { 721 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Yay, the worker responded after it was forked'</span>); 722});</code></pre> 723</section><section><h3>Event: <code>'setup'</code><span><a class="mark" href="#cluster_event_setup" id="cluster_event_setup">#</a></span></h3> 724<div class="api_metadata"> 725<span>Added in: v0.7.1</span> 726</div> 727<ul> 728<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 729</ul> 730<p>Emitted every time <a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> is called.</p> 731<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time 732<a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> was called and is advisory only, since multiple calls to 733<a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> can be made in a single tick.</p> 734<p>If accuracy is important, use <code>cluster.settings</code>.</p> 735</section><section><h3><code>cluster.disconnect([callback])</code><span><a class="mark" href="#cluster_cluster_disconnect_callback" id="cluster_cluster_disconnect_callback">#</a></span></h3> 736<div class="api_metadata"> 737<span>Added in: v0.7.7</span> 738</div> 739<ul> 740<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when all workers are disconnected and handles are 741closed.</li> 742</ul> 743<p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>.</p> 744<p>When they are disconnected all internal handles will be closed, allowing the 745master process to die gracefully if no other event is waiting.</p> 746<p>The method takes an optional callback argument which will be called when 747finished.</p> 748<p>This can only be called from the master process.</p> 749</section><section><h3><code>cluster.fork([env])</code><span><a class="mark" href="#cluster_cluster_fork_env" id="cluster_cluster_fork_env">#</a></span></h3> 750<div class="api_metadata"> 751<span>Added in: v0.6.0</span> 752</div> 753<ul> 754<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Key/value pairs to add to worker process environment.</li> 755<li>Returns: <a href="cluster.html#cluster_class_worker" class="type"><cluster.Worker></a></li> 756</ul> 757<p>Spawn a new worker process.</p> 758<p>This can only be called from the master process.</p> 759</section><section><h3><code>cluster.isMaster</code><span><a class="mark" href="#cluster_cluster_ismaster" id="cluster_cluster_ismaster">#</a></span></h3> 760<div class="api_metadata"> 761<span>Added in: v0.8.1</span> 762</div> 763<ul> 764<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 765</ul> 766<p>True if the process is a master. This is determined 767by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is 768undefined, then <code>isMaster</code> is <code>true</code>.</p> 769</section><section><h3><code>cluster.isWorker</code><span><a class="mark" href="#cluster_cluster_isworker" id="cluster_cluster_isworker">#</a></span></h3> 770<div class="api_metadata"> 771<span>Added in: v0.6.0</span> 772</div> 773<ul> 774<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 775</ul> 776<p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).</p> 777</section><section><h3><code>cluster.schedulingPolicy</code><span><a class="mark" href="#cluster_cluster_schedulingpolicy" id="cluster_cluster_schedulingpolicy">#</a></span></h3> 778<div class="api_metadata"> 779<span>Added in: v0.11.2</span> 780</div> 781<p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or 782<code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a 783global setting and effectively frozen once either the first worker is spawned, 784or <a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> is called, whichever comes first.</p> 785<p><code>SCHED_RR</code> is the default on all operating systems except Windows. 786Windows will change to <code>SCHED_RR</code> once libuv is able to effectively 787distribute IOCP handles without incurring a large performance hit.</p> 788<p><code>cluster.schedulingPolicy</code> can also be set through the 789<code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid 790values are <code>'rr'</code> and <code>'none'</code>.</p> 791</section><section><h3><code>cluster.settings</code><span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h3> 792<div class="api_metadata"> 793<details class="changelog"><summary>History</summary> 794<table> 795<tbody><tr><th>Version</th><th>Changes</th></tr> 796<tr><td>v13.2.0, v12.16.0</td> 797<td><p>The <code>serialization</code> option is supported now.</p></td></tr> 798<tr><td>v9.5.0</td> 799<td><p>The <code>cwd</code> option is supported now.</p></td></tr> 800<tr><td>v9.4.0</td> 801<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> 802<tr><td>v8.2.0</td> 803<td><p>The <code>inspectPort</code> option is supported now.</p></td></tr> 804<tr><td>v6.4.0</td> 805<td><p>The <code>stdio</code> option is supported now.</p></td></tr> 806<tr><td>v0.7.1</td> 807<td><p><span>Added in: v0.7.1</span></p></td></tr> 808</tbody></table> 809</details> 810</div> 811<ul> 812<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 813<ul> 814<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments passed to the Node.js 815executable. <strong>Default:</strong> <code>process.execArgv</code>.</li> 816<li><code>exec</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> File path to worker file. <strong>Default:</strong> <code>process.argv[1]</code>.</li> 817<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> String arguments passed to worker. 818<strong>Default:</strong> <code>process.argv.slice(2)</code>.</li> 819<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the worker process. <strong>Default:</strong> 820<code>undefined</code> (inherits from parent process).</li> 821<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specify the kind of serialization used for sending 822messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>. 823See <a href="child_process.html#child_process_advanced_serialization">Advanced serialization for <code>child_process</code></a> for more details. 824<strong>Default:</strong> <code>false</code>.</li> 825<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not to send output to parent's stdio. 826<strong>Default:</strong> <code>false</code>.</li> 827<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Configures the stdio of forked processes. Because the 828cluster module relies on IPC to function, this configuration must contain an 829<code>'ipc'</code> entry. When this option is provided, it overrides <code>silent</code>.</li> 830<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.)</li> 831<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.)</li> 832<li><code>inspectPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Sets inspector port of worker. 833This can be a number, or a function that takes no arguments and returns a 834number. By default each worker gets its own port, incremented from the 835master's <code>process.debugPort</code>.</li> 836<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the forked processes console window that would 837normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> 838</ul> 839</li> 840</ul> 841<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 842contain the settings, including the default values.</p> 843<p>This object is not intended to be changed or set manually.</p> 844</section><section><h3><code>cluster.setupMaster([settings])</code><span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h3> 845<div class="api_metadata"> 846<details class="changelog"><summary>History</summary> 847<table> 848<tbody><tr><th>Version</th><th>Changes</th></tr> 849<tr><td>v6.4.0</td> 850<td><p>The <code>stdio</code> option is supported now.</p></td></tr> 851<tr><td>v0.7.1</td> 852<td><p><span>Added in: v0.7.1</span></p></td></tr> 853</tbody></table> 854</details> 855</div> 856<ul> 857<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#cluster_cluster_settings"><code>cluster.settings</code></a>.</li> 858</ul> 859<p><code>setupMaster</code> is used to change the default 'fork' behavior. Once called, 860the settings will be present in <code>cluster.settings</code>.</p> 861<p>Any settings changes only affect future calls to <a href="#cluster_cluster_fork_env"><code>.fork()</code></a> and have no 862effect on workers that are already running.</p> 863<p>The only attribute of a worker that cannot be set via <code>.setupMaster()</code> is 864the <code>env</code> passed to <a href="#cluster_cluster_fork_env"><code>.fork()</code></a>.</p> 865<p>The defaults above apply to the first call only; the defaults for later 866calls are the current values at the time of <code>cluster.setupMaster()</code> is called.</p> 867<pre><code class="language-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>); 868cluster.<span class="hljs-title function_">setupMaster</span>({ 869 <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>, 870 <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>], 871 <span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span> 872}); 873cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span> 874cluster.<span class="hljs-title function_">setupMaster</span>({ 875 <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>, 876 <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>] 877}); 878cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code></pre> 879<p>This can only be called from the master process.</p> 880</section><section><h3><code>cluster.worker</code><span><a class="mark" href="#cluster_cluster_worker" id="cluster_cluster_worker">#</a></span></h3> 881<div class="api_metadata"> 882<span>Added in: v0.7.0</span> 883</div> 884<ul> 885<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 886</ul> 887<p>A reference to the current worker object. Not available in the master process.</p> 888<pre><code class="language-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>); 889 890<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) { 891 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am master'</span>); 892 cluster.<span class="hljs-title function_">fork</span>(); 893 cluster.<span class="hljs-title function_">fork</span>(); 894} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) { 895 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`I am worker #<span class="hljs-subst">${cluster.worker.id}</span>`</span>); 896}</code></pre> 897</section><section><h3><code>cluster.workers</code><span><a class="mark" href="#cluster_cluster_workers" id="cluster_cluster_workers">#</a></span></h3> 898<div class="api_metadata"> 899<span>Added in: v0.7.0</span> 900</div> 901<ul> 902<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 903</ul> 904<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it 905easy to loop through all the workers. It is only available in the master 906process.</p> 907<p>A worker is removed from <code>cluster.workers</code> after the worker has disconnected 908<em>and</em> exited. The order between these two events cannot be determined in 909advance. However, it is guaranteed that the removal from the <code>cluster.workers</code> 910list happens before last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p> 911<pre><code class="language-js"><span class="hljs-comment">// Go through all workers</span> 912<span class="hljs-keyword">function</span> <span class="hljs-title function_">eachWorker</span>(<span class="hljs-params">callback</span>) { 913 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> id <span class="hljs-keyword">in</span> cluster.<span class="hljs-property">workers</span>) { 914 <span class="hljs-title function_">callback</span>(cluster.<span class="hljs-property">workers</span>[id]); 915 } 916} 917<span class="hljs-title function_">eachWorker</span>(<span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> { 918 worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>); 919});</code></pre> 920<p>Using the worker's unique id is the easiest way to locate the worker.</p> 921<pre><code class="language-js">socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">id</span>) =></span> { 922 <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-property">workers</span>[id]; 923});</code></pre></section> 924 <!-- API END --> 925 </div> 926 </div> 927 </div> 928 <script> 929 'use strict'; 930 { 931 const kCustomPreference = 'customDarkTheme'; 932 const userSettings = sessionStorage.getItem(kCustomPreference); 933 const themeToggleButton = document.getElementById('theme-toggle-btn'); 934 if (userSettings === null && window.matchMedia) { 935 const mq = window.matchMedia('(prefers-color-scheme: dark)'); 936 if ('onchange' in mq) { 937 function mqChangeListener(e) { 938 document.body.classList.toggle('dark-mode', e.matches); 939 } 940 mq.addEventListener('change', mqChangeListener); 941 if (themeToggleButton) { 942 themeToggleButton.addEventListener('click', function() { 943 mq.removeEventListener('change', mqChangeListener); 944 }, { once: true }); 945 } 946 } 947 if (mq.matches) { 948 document.body.classList.add('dark-mode'); 949 } 950 } else if (userSettings === 'true') { 951 document.body.classList.add('dark-mode'); 952 } 953 if (themeToggleButton) { 954 themeToggleButton.hidden = false; 955 themeToggleButton.addEventListener('click', function() { 956 sessionStorage.setItem( 957 kCustomPreference, 958 document.body.classList.toggle('dark-mode') 959 ); 960 }); 961 } 962 } 963 </script> 964</body> 965</html> 966