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