cluster.html 34.7 KB
Newer Older
1 2 3 4
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
5
  <title>Cluster Node.js v5.5.0 Manual &amp; Documentation</title>
6
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
7 8
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
9
  <link rel="canonical" href="https://nodejs.org/api/cluster.html">
10
</head>
11 12 13 14 15 16 17 18
<body class="alt apidoc" id="api-section-cluster">
  <div id="content" class="clearfix">
    <div id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js (1)
        </a>
      </div>
19
      <ul>
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Synopsis</a></li>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons" href="addons.html">C/C++ Addons</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster active" href="cluster.html">Cluster</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-modules" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>

60
    </div>
61 62 63

    <div id="column1" data-id="cluster" class="interior">
      <header>
64
        <h1>Node.js v5.5.0 Documentation</h1>
65 66 67 68 69 70 71 72 73 74 75 76 77
        <div id="gtoc">
          <p>
            <a href="index.html" name="toc">Index</a> |
            <a href="all.html">View on single page</a> |
            <a href="cluster.json">View as JSON</a>
          </p>
        </div>
        <hr>
      </header>

      <div id="toc">
        <h2>Table of Contents</h2>
        <ul>
78 79
<li><a href="#cluster_cluster">Cluster</a><ul>
<li><a href="#cluster_how_it_works">How It Works</a></li>
80
<li><a href="#cluster_class_worker">Class: Worker</a><ul>
81
<li><a href="#cluster_event_disconnect">Event: &#39;disconnect&#39;</a></li>
82
<li><a href="#cluster_event_error">Event: &#39;error&#39;</a></li>
83
<li><a href="#cluster_event_exit">Event: &#39;exit&#39;</a></li>
84
<li><a href="#cluster_event_listening">Event: &#39;listening&#39;</a></li>
85
<li><a href="#cluster_event_message">Event: &#39;message&#39;</a></li>
86 87
<li><a href="#cluster_event_online">Event: &#39;online&#39;</a></li>
<li><a href="#cluster_worker_disconnect">worker.disconnect()</a></li>
88
<li><a href="#cluster_worker_id">worker.id</a></li>
89 90 91
<li><a href="#cluster_worker_isconnected">worker.isConnected()</a></li>
<li><a href="#cluster_worker_isdead">worker.isDead()</a></li>
<li><a href="#cluster_worker_kill_signal_sigterm">worker.kill([signal=&#39;SIGTERM&#39;])</a></li>
92
<li><a href="#cluster_worker_process">worker.process</a></li>
93
<li><a href="#cluster_worker_send_message_sendhandle_callback">worker.send(message[, sendHandle][, callback])</a></li>
94
<li><a href="#cluster_worker_suicide">worker.suicide</a></li>
95 96
</ul>
</li>
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
<li><a href="#cluster_event_disconnect_1">Event: &#39;disconnect&#39;</a></li>
<li><a href="#cluster_event_exit_1">Event: &#39;exit&#39;</a></li>
<li><a href="#cluster_event_fork">Event: &#39;fork&#39;</a></li>
<li><a href="#cluster_event_listening_1">Event: &#39;listening&#39;</a></li>
<li><a href="#cluster_event_message_1">Event: &#39;message&#39;</a></li>
<li><a href="#cluster_event_online_1">Event: &#39;online&#39;</a></li>
<li><a href="#cluster_event_setup">Event: &#39;setup&#39;</a></li>
<li><a href="#cluster_cluster_disconnect_callback">cluster.disconnect([callback])</a></li>
<li><a href="#cluster_cluster_fork_env">cluster.fork([env])</a></li>
<li><a href="#cluster_cluster_ismaster">cluster.isMaster</a></li>
<li><a href="#cluster_cluster_isworker">cluster.isWorker</a></li>
<li><a href="#cluster_cluster_schedulingpolicy">cluster.schedulingPolicy</a></li>
<li><a href="#cluster_cluster_settings">cluster.settings</a></li>
<li><a href="#cluster_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li>
<li><a href="#cluster_cluster_worker">cluster.worker</a></li>
<li><a href="#cluster_cluster_workers">cluster.workers</a></li>
113 114 115 116
</ul>
</li>
</ul>

117
      </div>
118

119 120 121 122
      <div id="apicontent">
        <h1>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Stable</pre><p>A single instance of Node.js runs in a single thread. To take advantage of
multi-core systems the user will sometimes want to launch a cluster of Node.js
123 124 125
processes to handle the load.

</p>
126
<p>The cluster module allows you to easily create child processes that
127 128 129
all share server ports.

</p>
130 131 132
<pre><code>const cluster = require(&#39;cluster&#39;);
const http = require(&#39;http&#39;);
const numCPUs = require(&#39;os&#39;).cpus().length;
133 134 135 136 137 138 139

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i &lt; numCPUs; i++) {
    cluster.fork();
  }

140 141
  cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {
    console.log(`worker ${worker.process.pid} died`);
142 143 144
  });
} else {
  // Workers can share any TCP connection
145
  // In this case it is an HTTP server
146
  http.createServer((req, res) =&gt; {
147
    res.writeHead(200);
148
    res.end(&#39;hello world\n&#39;);
149 150
  }).listen(8000);
}</code></pre>
151
<p>Running Node.js will now share port 8000 between the workers:
152 153

</p>
154 155 156 157 158
<pre><code>% NODE_DEBUG=cluster node server.js
23521,Master Worker 23524 online
23521,Master Worker 23526 online
23521,Master Worker 23523 online
23521,Master Worker 23528 online</code></pre>
159
<p>Please note that, on Windows, it is not yet possible to set up a named pipe
160 161 162 163 164 165
server in a worker.

</p>
<h2>How It Works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h2>
<!--type=misc-->

166
<p>The worker processes are spawned using the [<code>child_process.fork</code>][] method,
167 168 169 170
so that they can communicate with the parent via IPC and pass server
handles back and forth.

</p>
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
<p>The cluster module supports two methods of distributing incoming
connections.

</p>
<p>The first one (and the default one on all platforms except Windows),
is the round-robin approach, where the master process listens on a
port, accepts new connections and distributes them across the workers
in a round-robin fashion, with some built-in smarts to avoid
overloading a worker process.

</p>
<p>The second approach is where the master process creates the listen
socket and sends it to interested workers. The workers then accept
incoming connections directly.

</p>
<p>The second approach should, in theory, give the best performance.
In practice however, distribution tends to be very unbalanced due
to operating system scheduler vagaries. Loads have been observed
where over 70% of all connections ended up in just two processes,
out of a total of eight.
192 193

</p>
194 195 196
<p>Because <code>server.listen()</code> hands off most of the work to the master
process, there are three cases where the behavior between a normal
Node.js process and a cluster worker differs:
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

</p>
<ol>
<li><code>server.listen({fd: 7})</code> Because the message is passed to the master,
file descriptor 7 <strong>in the parent</strong> will be listened on, and the
handle passed to the worker, rather than listening to the worker&#39;s
idea of what the number 7 file descriptor references.</li>
<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
the worker to use the supplied handle, rather than talk to the master
process.  If the worker already has the handle, then it&#39;s presumed
that you know what you are doing.</li>
<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
random port.  However, in a cluster, each worker will receive the
same &quot;random&quot; port each time they do <code>listen(0)</code>.  In essence, the
port is random the first time, but predictable thereafter.  If you
want to listen on a unique port, generate a port number based on the
cluster worker ID.</li>
</ol>
215 216 217 218
<p>There is no routing logic in Node.js, or in your program, and no shared
state between the workers.  Therefore, it is important to design your
program such that it does not rely too heavily on in-memory data objects
for things like sessions and login.
219 220 221 222 223

</p>
<p>Because workers are all separate processes, they can be killed or
re-spawned depending on your program&#39;s needs, without affecting other
workers.  As long as there are some workers still alive, the server will
224 225 226 227 228 229
continue to accept connections.  If no workers are alive, existing connections
will be dropped and new connections will be refused.  Node.js does not
automatically manage the number of workers for you, however.  It is your
responsibility to manage the worker pool for your application&#39;s needs.


230 231

</p>
232 233 234 235
<h2>Class: Worker<span><a class="mark" href="#cluster_class_worker" id="cluster_class_worker">#</a></span></h2>
<p>A Worker object contains all public information and method about a worker.
In the master it can be obtained using <code>cluster.workers</code>. In a worker
it can be obtained using <code>cluster.worker</code>.
236 237

</p>
238 239
<h3>Event: &#39;disconnect&#39;<span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h3>
<p>Similar to the <code>cluster.on(&#39;disconnect&#39;)</code> event, but specific to this worker.
240 241

</p>
242
<pre><code>cluster.fork().on(&#39;disconnect&#39;, () =&gt; {
243 244 245
  // Worker has disconnected
});</code></pre>
<h3>Event: &#39;error&#39;<span><a class="mark" href="#cluster_event_error" id="cluster_event_error">#</a></span></h3>
246
<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>.
247 248

</p>
249
<p>In a worker you can also use <code>process.on(&#39;error&#39;)</code>.
250 251

</p>
252
<h3>Event: &#39;exit&#39;<span><a class="mark" href="#cluster_event_exit" id="cluster_event_exit">#</a></span></h3>
253
<div class="signature"><ul>
254 255 256
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>&#39;SIGHUP&#39;</code>) that caused
the process to be killed.</li>
257
</div></ul>
258
<p>Similar to the <code>cluster.on(&#39;exit&#39;)</code> event, but specific to this worker.
259 260

</p>
261 262
<pre><code>const worker = cluster.fork();
worker.on(&#39;exit&#39;, (code, signal) =&gt; {
263
  if( signal ) {
264
    console.log(`worker was killed by signal: ${signal}`);
265
  } else if( code !== 0 ) {
266
    console.log(`worker exited with error code: ${code}`);
267
  } else {
268
    console.log(&#39;worker success!&#39;);
269 270 271
  }
});</code></pre>
<h3>Event: &#39;listening&#39;<span><a class="mark" href="#cluster_event_listening" id="cluster_event_listening">#</a></span></h3>
272
<div class="signature"><ul>
273
<li><code>address</code> <span class="type">Object</span></li>
274
</div></ul>
275
<p>Similar to the <code>cluster.on(&#39;listening&#39;)</code> event, but specific to this worker.
276 277

</p>
278
<pre><code>cluster.fork().on(&#39;listening&#39;, (address) =&gt; {
279
  // Worker is listening
280
});</code></pre>
281
<p>It is not emitted in the worker.
282 283

</p>
284
<h3>Event: &#39;message&#39;<span><a class="mark" href="#cluster_event_message" id="cluster_event_message">#</a></span></h3>
285
<div class="signature"><ul>
286
<li><code>message</code> <span class="type">Object</span></li>
287
</div></ul>
288
<p>Similar to the <code>cluster.on(&#39;message&#39;)</code> event, but specific to this worker.
289 290

</p>
291
<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>.
292 293

</p>
294
<p>In a worker you can also use <code>process.on(&#39;message&#39;)</code>.
295 296

</p>
297 298
<p>As an example, here is a cluster that keeps count of the number of requests
in the master process using the message system:
299 300

</p>
301 302
<pre><code>const cluster = require(&#39;cluster&#39;);
const http = require(&#39;http&#39;);
303

304
if (cluster.isMaster) {
305

306 307
  // Keep track of http requests
  var numReqs = 0;
308 309
  setInterval(() =&gt; {
    console.log(&#39;numReqs =&#39;, numReqs);
310 311 312 313 314 315 316 317 318 319
  }, 1000);

  // Count requests
  function messageHandler(msg) {
    if (msg.cmd &amp;&amp; msg.cmd == &#39;notifyRequest&#39;) {
      numReqs += 1;
    }
  }

  // Start workers and listen for messages containing notifyRequest
320
  const numCPUs = require(&#39;os&#39;).cpus().length;
321 322 323 324
  for (var i = 0; i &lt; numCPUs; i++) {
    cluster.fork();
  }

325
  Object.keys(cluster.workers).forEach((id) =&gt; {
326 327 328 329 330 331
    cluster.workers[id].on(&#39;message&#39;, messageHandler);
  });

} else {

  // Worker processes have a http server.
332
  http.Server((req, res) =&gt; {
333
    res.writeHead(200);
334
    res.end(&#39;hello world\n&#39;);
335 336 337 338 339 340 341

    // notify master about the request
    process.send({ cmd: &#39;notifyRequest&#39; });
  }).listen(8000);
}</code></pre>
<h3>Event: &#39;online&#39;<span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h3>
<p>Similar to the <code>cluster.on(&#39;online&#39;)</code> event, but specific to this worker.
342 343

</p>
344
<pre><code>cluster.fork().on(&#39;online&#39;, () =&gt; {
345
  // Worker is online
346
});</code></pre>
347
<p>It is not emitted in the worker.
348

349
</p>
350
<h3>worker.disconnect()<span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h3>
351
<p>In a worker, this function will close all servers, wait for the <code>&#39;close&#39;</code> event on
352
those servers, and then disconnect the IPC channel.
353 354

</p>
355 356
<p>In the master, an internal message is sent to the worker causing it to call
<code>.disconnect()</code> on itself.
357

358
</p>
359
<p>Causes <code>.suicide</code> to be set.
360 361

</p>
362 363 364
<p>Note that after a server is closed, it will no longer accept new connections,
but connections may be accepted by any other listening worker. Existing
connections will be allowed to close as usual. When no more connections exist,
365
see [server.close()][], the IPC channel to the worker will close allowing it to
366
die gracefully.
367 368

</p>
369 370 371
<p>The above applies <em>only</em> to server connections, client connections are not
automatically closed by workers, and disconnect does not wait for them to close
before exiting.
372 373

</p>
374
<p>Note that in a worker, <code>process.disconnect</code> exists, but it is not this function,
375
it is <a href="child_process.html#child_process_child_disconnect"><code>disconnect</code></a>.
376 377

</p>
378 379 380
<p>Because long living server connections may block workers from disconnecting, it
may be useful to send a message, so application specific actions may be taken to
close them. It also may be useful to implement a timeout, killing a worker if
381
the <code>&#39;disconnect&#39;</code> event has not been emitted after some time.
382 383

</p>
384 385 386
<pre><code>if (cluster.isMaster) {
  var worker = cluster.fork();
  var timeout;
387

388
  worker.on(&#39;listening&#39;, (address) =&gt; {
389 390
    worker.send(&#39;shutdown&#39;);
    worker.disconnect();
391
    timeout = setTimeout(() =&gt; {
392 393 394
      worker.kill();
    }, 2000);
  });
395

396
  worker.on(&#39;disconnect&#39;, () =&gt; {
397 398
    clearTimeout(timeout);
  });
399

400
} else if (cluster.isWorker) {
401 402
  const net = require(&#39;net&#39;);
  var server = net.createServer((socket) =&gt; {
403 404
    // connections never end
  });
405

406 407
  server.listen(8000);

408
  process.on(&#39;message&#39;, (msg) =&gt; {
409 410 411 412 413 414
    if(msg === &#39;shutdown&#39;) {
      // initiate graceful close of any connections to server
    }
  });
}</code></pre>
<h3>worker.id<span><a class="mark" href="#cluster_worker_id" id="cluster_worker_id">#</a></span></h3>
415
<div class="signature"><ul>
416
<li><span class="type">Number</span></li>
417
</div></ul>
418 419
<p>Each new worker is given its own unique id, this id is stored in the
<code>id</code>.
420 421

</p>
422 423
<p>While a worker is alive, this is the key that indexes it in
cluster.workers
424

425
</p>
426 427 428
<h3>worker.isConnected()<span><a class="mark" href="#cluster_worker_isconnected" id="cluster_worker_isconnected">#</a></span></h3>
<p>This function returns <code>true</code> if the worker is connected to its master via its IPC
channel, <code>false</code> otherwise. A worker is connected to its master after it&#39;s been
429
created. It is disconnected after the <code>&#39;disconnect&#39;</code> event is emitted.
430

431
</p>
432 433 434
<h3>worker.isDead()<span><a class="mark" href="#cluster_worker_isdead" id="cluster_worker_isdead">#</a></span></h3>
<p>This function returns <code>true</code> if the worker&#39;s process has terminated (either
because of exiting or being signaled). Otherwise, it returns <code>false</code>.
435 436

</p>
437
<h3>worker.kill([signal=&#39;SIGTERM&#39;])<span><a class="mark" href="#cluster_worker_kill_signal_sigterm" id="cluster_worker_kill_signal_sigterm">#</a></span></h3>
438
<div class="signature"><ul>
439 440
<li><code>signal</code> <span class="type">String</span> Name of the kill signal to send to the worker
process.</li>
441
</div></ul>
442 443 444
<p>This function will kill the worker. In the master, it does this by disconnecting
the <code>worker.process</code>, and once disconnected, killing with <code>signal</code>. In the
worker, it does it by disconnecting the channel, and then exiting with code <code>0</code>.
445 446

</p>
447
<p>Causes <code>.suicide</code> to be set.
448 449

</p>
450
<p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.
451 452

</p>
453
<p>Note that in a worker, <code>process.kill()</code> exists, but it is not this function,
454
it is <a href="process.html#process_process_kill_pid_signal"><code>kill</code></a>.
455 456 457 458 459 460

</p>
<h3>worker.process<span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">ChildProcess object</span></li>
</div></ul>
461
<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
462 463 464 465 466
from this function is stored as <code>.process</code>. In a worker, the global <code>process</code>
is stored.

</p>
<p>See: <a href="child_process.html#child_process_child_process_fork_modulepath_args_options">Child Process module</a>
467 468

</p>
469 470 471
<p>Note that workers will call <code>process.exit(0)</code> if the <code>&#39;disconnect&#39;</code> event occurs
on <code>process</code> and <code>.suicide</code> is not <code>true</code>. This protects against accidental
disconnection.
472 473

</p>
474
<h3>worker.send(message[, sendHandle][, callback])<span><a class="mark" href="#cluster_worker_send_message_sendhandle_callback" id="cluster_worker_send_message_sendhandle_callback">#</a></span></h3>
475 476 477
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span></li>
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
478 479
<li><code>callback</code> <span class="type">Function</span></li>
<li>Return: Boolean</li>
480
</div></ul>
481
<p>Send a message to a worker or master, optionally with a handle.
482 483

</p>
484
<p>In the master this sends a message to a specific worker. It is identical to
485
<a href="child_process.html#child_process_child_send_message_sendhandle_callback"><code>ChildProcess.send()</code></a>.
486 487 488 489

</p>
<p>In a worker this sends a message to the master. It is identical to
<code>process.send()</code>.
490 491 492 493 494 495 496 497 498 499

</p>
<p>This example will echo back all messages from the master:

</p>
<pre><code>if (cluster.isMaster) {
  var worker = cluster.fork();
  worker.send(&#39;hi there&#39;);

} else if (cluster.isWorker) {
500
  process.on(&#39;message&#39;, (msg) =&gt; {
501 502 503
    process.send(msg);
  });
}</code></pre>
504
<h3>worker.suicide<span><a class="mark" href="#cluster_worker_suicide" id="cluster_worker_suicide">#</a></span></h3>
505
<div class="signature"><ul>
506
<li><span class="type">Boolean</span></li>
507
</div></ul>
508
<p>Set by calling <code>.kill()</code> or <code>.disconnect()</code>, until then it is <code>undefined</code>.
509 510

</p>
511 512
<p>The boolean <code>worker.suicide</code> lets you distinguish between voluntary and accidental
exit, the master may choose not to respawn a worker based on this value.
513

514
</p>
515
<pre><code>cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {
516 517 518 519
  if (worker.suicide === true) {
    console.log(&#39;Oh, it was just suicide\&#39; – no need to worry&#39;).
  }
});
520

521 522 523 524 525 526 527 528 529
// kill worker
worker.kill();</code></pre>
<h2>Event: &#39;disconnect&#39;<span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
<p>Emitted after the worker IPC channel has disconnected. This can occur when a
worker exits gracefully, is killed, or is disconnected manually (such as with
worker.disconnect()).
530 531

</p>
532
<p>There may be a delay between the <code>&#39;disconnect&#39;</code> and <code>&#39;exit&#39;</code> events.  These events
533 534
can be used to detect if the process is stuck in a cleanup or if there are
long-living connections.
535 536

</p>
537 538
<pre><code>cluster.on(&#39;disconnect&#39;, (worker) =&gt; {
  console.log(`The worker #${worker.id} has disconnected`);
539 540 541 542 543 544 545 546
});</code></pre>
<h2>Event: &#39;exit&#39;<span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>&#39;SIGHUP&#39;</code>) that caused
the process to be killed.</li>
</div></ul>
547
<p>When any of the workers die the cluster module will emit the <code>&#39;exit&#39;</code> event.
548 549

</p>
550
<p>This can be used to restart the worker by calling <code>.fork()</code> again.
551 552

</p>
553
<pre><code>cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {
554 555 556 557 558
  console.log(&#39;worker %d died (%s). restarting...&#39;,
    worker.process.pid, signal || code);
  cluster.fork();
});</code></pre>
<p>See <a href="child_process.html#child_process_event_exit">child_process event: &#39;exit&#39;</a>.
559 560

</p>
561 562 563 564
<h2>Event: &#39;fork&#39;<span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
565
<p>When a new worker is forked the cluster module will emit a <code>&#39;fork&#39;</code> event.
566
This can be used to log worker activity, and create your own timeout.
567 568

</p>
569 570
<pre><code>var timeouts = [];
function errorMsg() {
571
  console.error(&#39;Something must be wrong with the connection ...&#39;);
572 573
}

574
cluster.on(&#39;fork&#39;, (worker) =&gt; {
575 576
  timeouts[worker.id] = setTimeout(errorMsg, 2000);
});
577
cluster.on(&#39;listening&#39;, (worker, address) =&gt; {
578 579
  clearTimeout(timeouts[worker.id]);
});
580
cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {
581 582 583 584 585 586 587 588
  clearTimeout(timeouts[worker.id]);
  errorMsg();
});</code></pre>
<h2>Event: &#39;listening&#39;<span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>address</code> <span class="type">Object</span></li>
</div></ul>
589 590
<p>After calling <code>listen()</code> from a worker, when the <code>&#39;listening&#39;</code> event is emitted on
the server, a <code>&#39;listening&#39;</code> event will also be emitted on <code>cluster</code> in the master.
591 592

</p>
593 594 595 596
<p>The event handler is executed with two arguments, the <code>worker</code> contains the worker
object and the <code>address</code> object contains the following connection properties:
<code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the worker is listening
on more than one address.
597 598

</p>
599 600 601
<pre><code>cluster.on(&#39;listening&#39;, (worker, address) =&gt; {
  console.log(
    `A worker is now connected to ${address.address}:${address.port}`);
602 603
});</code></pre>
<p>The <code>addressType</code> is one of:
604

605 606 607 608 609 610 611 612 613 614 615 616 617
</p>
<ul>
<li><code>4</code> (TCPv4)</li>
<li><code>6</code> (TCPv6)</li>
<li><code>-1</code> (unix domain socket)</li>
<li><code>&quot;udp4&quot;</code> or <code>&quot;udp6&quot;</code> (UDP v4 or v6)</li>
</ul>
<h2>Event: &#39;message&#39;<span><a class="mark" href="#cluster_event_message_1" id="cluster_event_message_1">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>message</code> <span class="type">Object</span></li>
</div></ul>
<p>Emitted when any worker receives a message.
618

619
</p>
620
<p>See <a href="child_process.html#child_process_event_message">child_process event: &#39;message&#39;</a>.
621

622 623 624 625 626 627 628
</p>
<h2>Event: &#39;online&#39;<span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
<p>After forking a new worker, the worker should respond with an online message.
When the master receives an online message it will emit this event.
629
The difference between <code>&#39;fork&#39;</code> and <code>&#39;online&#39;</code> is that fork is emitted when the
630
master forks a worker, and &#39;online&#39; is emitted when the worker is running.
631

632
</p>
633 634
<pre><code>cluster.on(&#39;online&#39;, (worker) =&gt; {
  console.log(&#39;Yay, the worker responded after it was forked&#39;);
635 636 637 638 639 640
});</code></pre>
<h2>Event: &#39;setup&#39;<span><a class="mark" href="#cluster_event_setup" id="cluster_event_setup">#</a></span></h2>
<div class="signature"><ul>
<li><code>settings</code> <span class="type">Object</span></li>
</div></ul>
<p>Emitted every time <code>.setupMaster()</code> is called.
641

642 643 644 645
</p>
<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time
<code>.setupMaster()</code> was called and is advisory only, since multiple calls to
<code>.setupMaster()</code> can be made in a single tick.
646 647

</p>
648
<p>If accuracy is important, use <code>cluster.settings</code>.
649 650

</p>
651
<h2>cluster.disconnect([callback])<span><a class="mark" href="#cluster_cluster_disconnect_callback" id="cluster_cluster_disconnect_callback">#</a></span></h2>
652
<div class="signature"><ul>
653 654
<li><code>callback</code> <span class="type">Function</span> called when all workers are disconnected and handles are
closed</li>
655
</div></ul>
656
<p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>.
657 658

</p>
659 660
<p>When they are disconnected all internal handles will be closed, allowing the
master process to die gracefully if no other event is waiting.
661 662

</p>
663
<p>The method takes an optional callback argument which will be called when finished.
664 665

</p>
666
<p>This can only be called from the master process.
667 668

</p>
669 670 671 672 673 674
<h2>cluster.fork([env])<span><a class="mark" href="#cluster_cluster_fork_env" id="cluster_cluster_fork_env">#</a></span></h2>
<div class="signature"><ul>
<li><code>env</code> <span class="type">Object</span> Key/value pairs to add to worker process environment.</li>
<li>return <span class="type">Worker object</span></li>
</div></ul>
<p>Spawn a new worker process.
675

676 677
</p>
<p>This can only be called from the master process.
678

679 680 681 682 683 684 685 686
</p>
<h2>cluster.isMaster<span><a class="mark" href="#cluster_cluster_ismaster" id="cluster_cluster_ismaster">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></ul>
<p>True if the process is a master. This is determined
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
undefined, then <code>isMaster</code> is <code>true</code>.
687

688 689 690 691 692 693
</p>
<h2>cluster.isWorker<span><a class="mark" href="#cluster_cluster_isworker" id="cluster_cluster_isworker">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></ul>
<p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).
694

695 696 697 698 699 700
</p>
<h2>cluster.schedulingPolicy<span><a class="mark" href="#cluster_cluster_schedulingpolicy" id="cluster_cluster_schedulingpolicy">#</a></span></h2>
<p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or
<code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a
global setting and effectively frozen once you spawn the first worker
or call <code>cluster.setupMaster()</code>, whatever comes first.
701

702 703 704 705
</p>
<p><code>SCHED_RR</code> is the default on all operating systems except Windows.
Windows will change to <code>SCHED_RR</code> once libuv is able to effectively
distribute IOCP handles without incurring a large performance hit.
706

707 708 709 710
</p>
<p><code>cluster.schedulingPolicy</code> can also be set through the
<code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid
values are <code>&quot;rr&quot;</code> and <code>&quot;none&quot;</code>.
711

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
</p>
<h2>cluster.settings<span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span><ul>
<li><code>execArgv</code> <span class="type">Array</span> list of string arguments passed to the Node.js
executable. (Default=<code>process.execArgv</code>)</li>
<li><code>exec</code> <span class="type">String</span> file path to worker file.  (Default=<code>process.argv[1]</code>)</li>
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent&#39;s stdio.
(Default=<code>false</code>)</li>
<li><code>uid</code> <span class="type">Number</span> Sets the user identity of the process. (See setuid(2).)</li>
<li><code>gid</code> <span class="type">Number</span> Sets the group identity of the process. (See setgid(2).)</li>
</ul>
</li>
</div></ul>
<p>After calling <code>.setupMaster()</code> (or <code>.fork()</code>) this settings object will contain
the settings, including the default values.
730

731 732 733
</p>
<p>It is effectively frozen after being set, because <code>.setupMaster()</code> can
only be called once.
734 735

</p>
736
<p>This object is not supposed to be changed or set manually, by you.
737 738

</p>
739
<h2>cluster.setupMaster([settings])<span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h2>
740
<div class="signature"><ul>
741 742 743 744 745 746 747 748
<li><code>settings</code> <span class="type">Object</span><ul>
<li><code>exec</code> <span class="type">String</span> file path to worker file.  (Default=<code>process.argv[1]</code>)</li>
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent&#39;s stdio.
(Default=<code>false</code>)</li>
</ul>
</li>
749
</div></ul>
750 751
<p><code>setupMaster</code> is used to change the default &#39;fork&#39; behavior. Once called,
the settings will be present in <code>cluster.settings</code>.
752 753

</p>
754
<p>Note that:
755 756

</p>
757 758 759 760 761 762 763 764 765
<ul>
<li>any settings changes only affect future calls to <code>.fork()</code> and have no
effect on workers that are already running</li>
<li>The <em>only</em> attribute of a worker that cannot be set via <code>.setupMaster()</code> is
the <code>env</code> passed to <code>.fork()</code></li>
<li>the defaults above apply to the first call only, the defaults for later
calls is the current value at the time of <code>cluster.setupMaster()</code> is called</li>
</ul>
<p>Example:
766 767

</p>
768
<pre><code>const cluster = require(&#39;cluster&#39;);
769 770 771 772 773 774 775 776 777 778 779 780 781 782
cluster.setupMaster({
  exec: &#39;worker.js&#39;,
  args: [&#39;--use&#39;, &#39;https&#39;],
  silent: true
});
cluster.fork(); // https worker
cluster.setupMaster({
  args: [&#39;--use&#39;, &#39;http&#39;]
});
cluster.fork(); // http worker</code></pre>
<p>This can only be called from the master process.

</p>
<h2>cluster.worker<span><a class="mark" href="#cluster_cluster_worker" id="cluster_cluster_worker">#</a></span></h2>
783
<div class="signature"><ul>
784
<li><span class="type">Object</span></li>
785
</div></ul>
786
<p>A reference to the current worker object. Not available in the master process.
787 788

</p>
789
<pre><code>const cluster = require(&#39;cluster&#39;);
790 791 792 793 794 795

if (cluster.isMaster) {
  console.log(&#39;I am master&#39;);
  cluster.fork();
  cluster.fork();
} else if (cluster.isWorker) {
796
  console.log(`I am worker #${cluster.worker.id}`);
797 798 799 800 801 802 803 804
}</code></pre>
<h2>cluster.workers<span><a class="mark" href="#cluster_cluster_workers" id="cluster_cluster_workers">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></ul>
<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it
easy to loop through all the workers. It is only available in the master
process.
805 806

</p>
807 808 809 810 811 812 813 814 815 816 817 818
<p>A worker is removed from cluster.workers after the worker has disconnected <em>and</em>
exited. The order between these two events cannot be determined in advance.
However, it is guaranteed that the removal from the cluster.workers list happens
before last <code>&#39;disconnect&#39;</code> or <code>&#39;exit&#39;</code> event is emitted.

</p>
<pre><code>// Go through all workers
function eachWorker(callback) {
  for (var id in cluster.workers) {
    callback(cluster.workers[id]);
  }
}
819
eachWorker((worker) =&gt; {
820 821 822 823
  worker.send(&#39;big announcement to all workers&#39;);
});</code></pre>
<p>Should you wish to reference a worker over a communication channel, using
the worker&#39;s unique id is the easiest way to find the worker.
824

825
</p>
826
<pre><code>socket.on(&#39;data&#39;, (id) =&gt; {
827 828
  var worker = cluster.workers[id];
});</code></pre>
829

830
      </div>
831
    </div>
832 833 834
  </div>
  <script src="assets/sh_main.js"></script>
  <script src="assets/sh_javascript.min.js"></script>
835 836 837 838
  <script>highlight(undefined, undefined, 'pre');</script>
</body>
</html>