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