xref: /third_party/node/doc/api/cluster.html (revision 1cb0ef41)
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="v18.20.1">
7  <title>Cluster | Node.js v18.20.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/cluster.html">
12  <script async defer src="assets/api.js" type="text/javascript"></script>
13  <style>@media(max-width:542px){.with-40-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:582px){.with-45-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style>
14</head>
15<body class="alt apidoc" id="api-section-cluster">
16  <div id="content" class="clearfix">
17    <div id="column2" class="interior">
18      <div id="intro" class="interior">
19        <a href="/" title="Go back to the home page">
20          Node.js
21        </a>
22      </div>
23      <ul>
24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
26</ul>
27<hr class="line">
28<ul>
29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
33<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
37<li><a href="cluster.html" class="nav-cluster active">Cluster</a></li>
38<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
39<li><a href="console.html" class="nav-console">Console</a></li>
40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
45<li><a href="dns.html" class="nav-dns">DNS</a></li>
46<li><a href="domain.html" class="nav-domain">Domain</a></li>
47<li><a href="errors.html" class="nav-errors">Errors</a></li>
48<li><a href="events.html" class="nav-events">Events</a></li>
49<li><a href="fs.html" class="nav-fs">File system</a></li>
50<li><a href="globals.html" class="nav-globals">Globals</a></li>
51<li><a href="http.html" class="nav-http">HTTP</a></li>
52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
53<li><a href="https.html" class="nav-https">HTTPS</a></li>
54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
55<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
60<li><a href="net.html" class="nav-net">Net</a></li>
61<li><a href="os.html" class="nav-os">OS</a></li>
62<li><a href="path.html" class="nav-path">Path</a></li>
63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
65<li><a href="process.html" class="nav-process">Process</a></li>
66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
68<li><a href="readline.html" class="nav-readline">Readline</a></li>
69<li><a href="repl.html" class="nav-repl">REPL</a></li>
70<li><a href="report.html" class="nav-report">Report</a></li>
71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
72<li><a href="stream.html" class="nav-stream">Stream</a></li>
73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
74<li><a href="test.html" class="nav-test">Test runner</a></li>
75<li><a href="timers.html" class="nav-timers">Timers</a></li>
76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
78<li><a href="tty.html" class="nav-tty">TTY</a></li>
79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
80<li><a href="url.html" class="nav-url">URL</a></li>
81<li><a href="util.html" class="nav-util">Utilities</a></li>
82<li><a href="v8.html" class="nav-v8">V8</a></li>
83<li><a href="vm.html" class="nav-vm">VM</a></li>
84<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
89</ul>
90<hr class="line">
91<ul>
92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
93</ul>
94    </div>
95
96    <div id="column1" data-id="cluster" class="interior">
97      <header class="header">
98        <div class="header-container">
99          <h1>Node.js v18.20.1 documentation</h1>
100          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
101            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
102              <path fill="none" d="M0 0h24v24H0z" />
103              <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"/>
104              <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"/>
105            </svg>
106            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
107              <path d="M0 0h24v24H0z" fill="none" />
108              <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"/>
109            </svg>
110          </button>
111        </div>
112        <div id="gtoc">
113          <ul>
114            <li class="pinned-header">Node.js v18.20.1</li>
115            
116    <li class="picker-header">
117      <a href="#">
118        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
119        Table of contents
120      </a>
121
122      <div class="picker"><div class="toc"><ul>
123<li><span class="stability_2"><a href="#cluster">Cluster</a></span>
124<ul>
125<li><a href="#how-it-works">How it works</a></li>
126<li><a href="#class-worker">Class: <code>Worker</code></a>
127<ul>
128<li><a href="#event-disconnect">Event: <code>'disconnect'</code></a></li>
129<li><a href="#event-error">Event: <code>'error'</code></a></li>
130<li><a href="#event-exit">Event: <code>'exit'</code></a></li>
131<li><a href="#event-listening">Event: <code>'listening'</code></a></li>
132<li><a href="#event-message">Event: <code>'message'</code></a></li>
133<li><a href="#event-online">Event: <code>'online'</code></a></li>
134<li><a href="#workerdisconnect"><code>worker.disconnect()</code></a></li>
135<li><a href="#workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a></li>
136<li><a href="#workerid"><code>worker.id</code></a></li>
137<li><a href="#workerisconnected"><code>worker.isConnected()</code></a></li>
138<li><a href="#workerisdead"><code>worker.isDead()</code></a></li>
139<li><a href="#workerkillsignal"><code>worker.kill([signal])</code></a></li>
140<li><a href="#workerprocess"><code>worker.process</code></a></li>
141<li><a href="#workersendmessage-sendhandle-options-callback"><code>worker.send(message[, sendHandle[, options]][, callback])</code></a></li>
142</ul>
143</li>
144<li><a href="#event-disconnect_1">Event: <code>'disconnect'</code></a></li>
145<li><a href="#event-exit_1">Event: <code>'exit'</code></a></li>
146<li><a href="#event-fork">Event: <code>'fork'</code></a></li>
147<li><a href="#event-listening_1">Event: <code>'listening'</code></a></li>
148<li><a href="#event-message_1">Event: <code>'message'</code></a></li>
149<li><a href="#event-online_1">Event: <code>'online'</code></a></li>
150<li><a href="#event-setup">Event: <code>'setup'</code></a></li>
151<li><a href="#clusterdisconnectcallback"><code>cluster.disconnect([callback])</code></a></li>
152<li><a href="#clusterforkenv"><code>cluster.fork([env])</code></a></li>
153<li><span class="stability_0"><a href="#clusterismaster"><code>cluster.isMaster</code></a></span></li>
154<li><a href="#clusterisprimary"><code>cluster.isPrimary</code></a></li>
155<li><a href="#clusterisworker"><code>cluster.isWorker</code></a></li>
156<li><a href="#clusterschedulingpolicy"><code>cluster.schedulingPolicy</code></a></li>
157<li><a href="#clustersettings"><code>cluster.settings</code></a></li>
158<li><span class="stability_0"><a href="#clustersetupmastersettings"><code>cluster.setupMaster([settings])</code></a></span></li>
159<li><a href="#clustersetupprimarysettings"><code>cluster.setupPrimary([settings])</code></a></li>
160<li><a href="#clusterworker"><code>cluster.worker</code></a></li>
161<li><a href="#clusterworkers"><code>cluster.workers</code></a></li>
162</ul>
163</li>
164</ul></div></div>
165    </li>
166  
167            
168    <li class="picker-header">
169      <a href="#">
170        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
171        Index
172      </a>
173
174      <div class="picker"><ul>
175<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
176<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
177
178      <li>
179        <a href="index.html">Index</a>
180      </li>
181    </ul>
182  
183<hr class="line">
184<ul>
185<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
186<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
187<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
188<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
189<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
190<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
191<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
192<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
193<li><a href="cluster.html" class="nav-cluster active">Cluster</a></li>
194<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
195<li><a href="console.html" class="nav-console">Console</a></li>
196<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
197<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
198<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
199<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
200<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
201<li><a href="dns.html" class="nav-dns">DNS</a></li>
202<li><a href="domain.html" class="nav-domain">Domain</a></li>
203<li><a href="errors.html" class="nav-errors">Errors</a></li>
204<li><a href="events.html" class="nav-events">Events</a></li>
205<li><a href="fs.html" class="nav-fs">File system</a></li>
206<li><a href="globals.html" class="nav-globals">Globals</a></li>
207<li><a href="http.html" class="nav-http">HTTP</a></li>
208<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
209<li><a href="https.html" class="nav-https">HTTPS</a></li>
210<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
211<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
212<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
213<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
214<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
215<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
216<li><a href="net.html" class="nav-net">Net</a></li>
217<li><a href="os.html" class="nav-os">OS</a></li>
218<li><a href="path.html" class="nav-path">Path</a></li>
219<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
220<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
221<li><a href="process.html" class="nav-process">Process</a></li>
222<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
223<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
224<li><a href="readline.html" class="nav-readline">Readline</a></li>
225<li><a href="repl.html" class="nav-repl">REPL</a></li>
226<li><a href="report.html" class="nav-report">Report</a></li>
227<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
228<li><a href="stream.html" class="nav-stream">Stream</a></li>
229<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
230<li><a href="test.html" class="nav-test">Test runner</a></li>
231<li><a href="timers.html" class="nav-timers">Timers</a></li>
232<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
233<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
234<li><a href="tty.html" class="nav-tty">TTY</a></li>
235<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
236<li><a href="url.html" class="nav-url">URL</a></li>
237<li><a href="util.html" class="nav-util">Utilities</a></li>
238<li><a href="v8.html" class="nav-v8">V8</a></li>
239<li><a href="vm.html" class="nav-vm">VM</a></li>
240<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
241<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
242<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
243<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
244<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
245</ul>
246<hr class="line">
247<ul>
248<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
249</ul></div>
250    </li>
251  
252            
253    <li class="picker-header">
254      <a href="#">
255        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
256        Other versions
257      </a>
258      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/cluster.html">21.x</a></li>
259<li><a href="https://nodejs.org/docs/latest-v20.x/api/cluster.html">20.x <b>LTS</b></a></li>
260<li><a href="https://nodejs.org/docs/latest-v19.x/api/cluster.html">19.x</a></li>
261<li><a href="https://nodejs.org/docs/latest-v18.x/api/cluster.html">18.x <b>LTS</b></a></li>
262<li><a href="https://nodejs.org/docs/latest-v17.x/api/cluster.html">17.x</a></li>
263<li><a href="https://nodejs.org/docs/latest-v16.x/api/cluster.html">16.x</a></li>
264<li><a href="https://nodejs.org/docs/latest-v15.x/api/cluster.html">15.x</a></li>
265<li><a href="https://nodejs.org/docs/latest-v14.x/api/cluster.html">14.x</a></li>
266<li><a href="https://nodejs.org/docs/latest-v13.x/api/cluster.html">13.x</a></li>
267<li><a href="https://nodejs.org/docs/latest-v12.x/api/cluster.html">12.x</a></li>
268<li><a href="https://nodejs.org/docs/latest-v11.x/api/cluster.html">11.x</a></li>
269<li><a href="https://nodejs.org/docs/latest-v10.x/api/cluster.html">10.x</a></li>
270<li><a href="https://nodejs.org/docs/latest-v9.x/api/cluster.html">9.x</a></li>
271<li><a href="https://nodejs.org/docs/latest-v8.x/api/cluster.html">8.x</a></li>
272<li><a href="https://nodejs.org/docs/latest-v7.x/api/cluster.html">7.x</a></li>
273<li><a href="https://nodejs.org/docs/latest-v6.x/api/cluster.html">6.x</a></li>
274<li><a href="https://nodejs.org/docs/latest-v5.x/api/cluster.html">5.x</a></li>
275<li><a href="https://nodejs.org/docs/latest-v4.x/api/cluster.html">4.x</a></li>
276<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/cluster.html">0.12.x</a></li>
277<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/cluster.html">0.10.x</a></li></ol></div>
278    </li>
279  
280            <li class="picker-header">
281              <a href="#">
282                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
283                Options
284              </a>
285        
286              <div class="picker">
287                <ul>
288                  <li>
289                    <a href="all.html">View on single page</a>
290                  </li>
291                  <li>
292                    <a href="cluster.json">View as JSON</a>
293                  </li>
294                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/cluster.md">Edit on GitHub</a></li>    
295                </ul>
296              </div>
297            </li>
298          </ul>
299        </div>
300        <hr>
301      </header>
302
303      <details id="toc" open><summary>Table of contents</summary><ul>
304<li><span class="stability_2"><a href="#cluster">Cluster</a></span>
305<ul>
306<li><a href="#how-it-works">How it works</a></li>
307<li><a href="#class-worker">Class: <code>Worker</code></a>
308<ul>
309<li><a href="#event-disconnect">Event: <code>'disconnect'</code></a></li>
310<li><a href="#event-error">Event: <code>'error'</code></a></li>
311<li><a href="#event-exit">Event: <code>'exit'</code></a></li>
312<li><a href="#event-listening">Event: <code>'listening'</code></a></li>
313<li><a href="#event-message">Event: <code>'message'</code></a></li>
314<li><a href="#event-online">Event: <code>'online'</code></a></li>
315<li><a href="#workerdisconnect"><code>worker.disconnect()</code></a></li>
316<li><a href="#workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a></li>
317<li><a href="#workerid"><code>worker.id</code></a></li>
318<li><a href="#workerisconnected"><code>worker.isConnected()</code></a></li>
319<li><a href="#workerisdead"><code>worker.isDead()</code></a></li>
320<li><a href="#workerkillsignal"><code>worker.kill([signal])</code></a></li>
321<li><a href="#workerprocess"><code>worker.process</code></a></li>
322<li><a href="#workersendmessage-sendhandle-options-callback"><code>worker.send(message[, sendHandle[, options]][, callback])</code></a></li>
323</ul>
324</li>
325<li><a href="#event-disconnect_1">Event: <code>'disconnect'</code></a></li>
326<li><a href="#event-exit_1">Event: <code>'exit'</code></a></li>
327<li><a href="#event-fork">Event: <code>'fork'</code></a></li>
328<li><a href="#event-listening_1">Event: <code>'listening'</code></a></li>
329<li><a href="#event-message_1">Event: <code>'message'</code></a></li>
330<li><a href="#event-online_1">Event: <code>'online'</code></a></li>
331<li><a href="#event-setup">Event: <code>'setup'</code></a></li>
332<li><a href="#clusterdisconnectcallback"><code>cluster.disconnect([callback])</code></a></li>
333<li><a href="#clusterforkenv"><code>cluster.fork([env])</code></a></li>
334<li><span class="stability_0"><a href="#clusterismaster"><code>cluster.isMaster</code></a></span></li>
335<li><a href="#clusterisprimary"><code>cluster.isPrimary</code></a></li>
336<li><a href="#clusterisworker"><code>cluster.isWorker</code></a></li>
337<li><a href="#clusterschedulingpolicy"><code>cluster.schedulingPolicy</code></a></li>
338<li><a href="#clustersettings"><code>cluster.settings</code></a></li>
339<li><span class="stability_0"><a href="#clustersetupmastersettings"><code>cluster.setupMaster([settings])</code></a></span></li>
340<li><a href="#clustersetupprimarysettings"><code>cluster.setupPrimary([settings])</code></a></li>
341<li><a href="#clusterworker"><code>cluster.worker</code></a></li>
342<li><a href="#clusterworkers"><code>cluster.workers</code></a></li>
343</ul>
344</li>
345</ul></details>
346
347      <div id="apicontent">
348        <h2>Cluster<span><a class="mark" href="#cluster" id="cluster">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster"></a></h2>
349
350<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
351<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v18.20.1/lib/cluster.js">lib/cluster.js</a></p>
352<p>Clusters of Node.js processes can be used to run multiple instances of Node.js
353that can distribute workloads among their application threads. When process
354isolation is not needed, use the <a href="worker_threads.html"><code>worker_threads</code></a> module instead, which
355allows running multiple application threads within a single Node.js instance.</p>
356<p>The cluster module allows easy creation of child processes that all share
357server ports.</p>
358
359<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
360<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
361<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
362<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
363
364<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
365
366<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
367  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
368
369  <span class="hljs-comment">// Fork workers.</span>
370  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
371    cluster.<span class="hljs-title function_">fork</span>();
372  }
373
374  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> {
375    <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>);
376  });
377} <span class="hljs-keyword">else</span> {
378  <span class="hljs-comment">// Workers can share any TCP connection</span>
379  <span class="hljs-comment">// In this case it is an HTTP server</span>
380  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
381    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
382    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
383  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
384
385  <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>);
386}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
387<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
388<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
389<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
390
391<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
392  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
393
394  <span class="hljs-comment">// Fork workers.</span>
395  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
396    cluster.<span class="hljs-title function_">fork</span>();
397  }
398
399  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> {
400    <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>);
401  });
402} <span class="hljs-keyword">else</span> {
403  <span class="hljs-comment">// Workers can share any TCP connection</span>
404  <span class="hljs-comment">// In this case it is an HTTP server</span>
405  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
406    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
407    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
408  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
409
410  <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>);
411}</code><button class="copy-button">copy</button></pre>
412<p>Running Node.js will now share port 8000 between the workers:</p>
413<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node server.js</span>
414Primary 3596 is running
415Worker 4324 started
416Worker 4520 started
417Worker 6056 started
418Worker 5644 started</code> <button class="copy-button">copy</button></pre>
419<p>On Windows, it is not yet possible to set up a named pipe server in a worker.</p>
420<section><h3>How it works<span><a class="mark" href="#how-it-works" id="how-it-works">#</a></span><a aria-hidden="true" class="legacy" id="cluster_how_it_works"></a></h3>
421
422<p>The worker processes are spawned using the <a href="child_process.html#child_processforkmodulepath-args-options"><code>child_process.fork()</code></a> method,
423so that they can communicate with the parent via IPC and pass server
424handles back and forth.</p>
425<p>The cluster module supports two methods of distributing incoming
426connections.</p>
427<p>The first one (and the default one on all platforms except Windows)
428is the round-robin approach, where the primary process listens on a
429port, accepts new connections and distributes them across the workers
430in a round-robin fashion, with some built-in smarts to avoid
431overloading a worker process.</p>
432<p>The second approach is where the primary process creates the listen
433socket and sends it to interested workers. The workers then accept
434incoming connections directly.</p>
435<p>The second approach should, in theory, give the best performance.
436In practice however, distribution tends to be very unbalanced due
437to operating system scheduler vagaries. Loads have been observed
438where over 70% of all connections ended up in just two processes,
439out of a total of eight.</p>
440<p>Because <code>server.listen()</code> hands off most of the work to the primary
441process, there are three cases where the behavior between a normal
442Node.js process and a cluster worker differs:</p>
443<ol>
444<li><code>server.listen({fd: 7})</code> Because the message is passed to the primary,
445file descriptor 7 <strong>in the parent</strong> will be listened on, and the
446handle passed to the worker, rather than listening to the worker's
447idea of what the number 7 file descriptor references.</li>
448<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
449the worker to use the supplied handle, rather than talk to the primary
450process.</li>
451<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
452random port. However, in a cluster, each worker will receive the
453same "random" port each time they do <code>listen(0)</code>. In essence, the
454port is random the first time, but predictable thereafter. To listen
455on a unique port, generate a port number based on the cluster worker ID.</li>
456</ol>
457<p>Node.js does not provide routing logic. It is therefore important to design an
458application such that it does not rely too heavily on in-memory data objects for
459things like sessions and login.</p>
460<p>Because workers are all separate processes, they can be killed or
461re-spawned depending on a program's needs, without affecting other
462workers. As long as there are some workers still alive, the server will
463continue to accept connections. If no workers are alive, existing connections
464will be dropped and new connections will be refused. Node.js does not
465automatically manage the number of workers, however. It is the application's
466responsibility to manage the worker pool based on its own needs.</p>
467<p>Although a primary use case for the <code>node:cluster</code> module is networking, it can
468also be used for other use cases requiring worker processes.</p>
469</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#class-worker" id="class-worker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_class_worker"></a></h3>
470<div class="api_metadata">
471<span>Added in: v0.7.0</span>
472</div>
473<ul>
474<li>Extends: <a href="events.html#class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
475</ul>
476<p>A <code>Worker</code> object contains all public information and method about a worker.
477In the primary it can be obtained using <code>cluster.workers</code>. In a worker
478it can be obtained using <code>cluster.worker</code>.</p>
479<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#event-disconnect" id="event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_disconnect"></a></h4>
480<div class="api_metadata">
481<span>Added in: v0.7.7</span>
482</div>
483<p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p>
484<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> {
485  <span class="hljs-comment">// Worker has disconnected</span>
486});</code> <button class="copy-button">copy</button></pre>
487<h4>Event: <code>'error'</code><span><a class="mark" href="#event-error" id="event-error">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_error"></a></h4>
488<div class="api_metadata">
489<span>Added in: v0.7.3</span>
490</div>
491<p>This event is the same as the one provided by <a href="child_process.html#child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
492<p>Within a worker, <code>process.on('error')</code> may also be used.</p>
493<h4>Event: <code>'exit'</code><span><a class="mark" href="#event-exit" id="event-exit">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_exit"></a></h4>
494<div class="api_metadata">
495<span>Added in: v0.11.2</span>
496</div>
497<ul>
498<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The exit code, if it exited normally.</li>
499<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused
500the process to be killed.</li>
501</ul>
502<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p>
503
504<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
505
506<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
507  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
508  worker.<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> {
509    <span class="hljs-keyword">if</span> (signal) {
510      <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>);
511    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
512      <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>);
513    } <span class="hljs-keyword">else</span> {
514      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>);
515    }
516  });
517}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
518
519<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
520  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
521  worker.<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> {
522    <span class="hljs-keyword">if</span> (signal) {
523      <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>);
524    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
525      <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>);
526    } <span class="hljs-keyword">else</span> {
527      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>);
528    }
529  });
530}</code><button class="copy-button">copy</button></pre>
531<h4>Event: <code>'listening'</code><span><a class="mark" href="#event-listening" id="event-listening">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_listening"></a></h4>
532<div class="api_metadata">
533<span>Added in: v0.7.0</span>
534</div>
535<ul>
536<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
537</ul>
538<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p>
539
540<pre class="with-45-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs">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> {
541  <span class="hljs-comment">// Worker is listening</span>
542});</code><code class="language-js cjs">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> {
543  <span class="hljs-comment">// Worker is listening</span>
544});</code><button class="copy-button">copy</button></pre>
545<p>It is not emitted in the worker.</p>
546<h4>Event: <code>'message'</code><span><a class="mark" href="#event-message" id="event-message">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_message"></a></h4>
547<div class="api_metadata">
548<span>Added in: v0.7.0</span>
549</div>
550<ul>
551<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
552<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
553</ul>
554<p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p>
555<p>Within a worker, <code>process.on('message')</code> may also be used.</p>
556<p>See <a href="process.html#event-message"><code>process</code> event: <code>'message'</code></a>.</p>
557<p>Here is an example using the message system. It keeps a count in the primary
558process of the number of HTTP requests received by the workers:</p>
559
560<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
561<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
562<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
563<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
564
565<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
566
567  <span class="hljs-comment">// Keep track of http requests</span>
568  <span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>;
569  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
570    <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>);
571  }, <span class="hljs-number">1000</span>);
572
573  <span class="hljs-comment">// Count requests</span>
574  <span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) {
575    <span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> &#x26;&#x26; msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) {
576      numReqs += <span class="hljs-number">1</span>;
577    }
578  }
579
580  <span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span>
581  <span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
582  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
583    cluster.<span class="hljs-title function_">fork</span>();
584  }
585
586  <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>) {
587    cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler);
588  }
589
590} <span class="hljs-keyword">else</span> {
591
592  <span class="hljs-comment">// Worker processes have a http server.</span>
593  http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
594    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
595    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
596
597    <span class="hljs-comment">// Notify primary about the request</span>
598    process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> });
599  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
600}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
601<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
602<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
603
604<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
605
606  <span class="hljs-comment">// Keep track of http requests</span>
607  <span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>;
608  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
609    <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>);
610  }, <span class="hljs-number">1000</span>);
611
612  <span class="hljs-comment">// Count requests</span>
613  <span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) {
614    <span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> &#x26;&#x26; msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) {
615      numReqs += <span class="hljs-number">1</span>;
616    }
617  }
618
619  <span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span>
620  <span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
621  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
622    cluster.<span class="hljs-title function_">fork</span>();
623  }
624
625  <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>) {
626    cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler);
627  }
628
629} <span class="hljs-keyword">else</span> {
630
631  <span class="hljs-comment">// Worker processes have a http server.</span>
632  http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
633    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
634    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
635
636    <span class="hljs-comment">// Notify primary about the request</span>
637    process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> });
638  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
639}</code><button class="copy-button">copy</button></pre>
640<h4>Event: <code>'online'</code><span><a class="mark" href="#event-online" id="event-online">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_online"></a></h4>
641<div class="api_metadata">
642<span>Added in: v0.7.0</span>
643</div>
644<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p>
645<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> {
646  <span class="hljs-comment">// Worker is online</span>
647});</code> <button class="copy-button">copy</button></pre>
648<p>It is not emitted in the worker.</p>
649<h4><code>worker.disconnect()</code><span><a class="mark" href="#workerdisconnect" id="workerdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_disconnect"></a></h4>
650<div class="api_metadata">
651<details class="changelog"><summary>History</summary>
652<table>
653<tbody><tr><th>Version</th><th>Changes</th></tr>
654<tr><td>v7.3.0</td>
655<td><p>This method now returns a reference to <code>worker</code>.</p></td></tr>
656<tr><td>v0.7.7</td>
657<td><p><span>Added in: v0.7.7</span></p></td></tr>
658</tbody></table>
659</details>
660</div>
661<ul>
662<li>Returns: <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a> A reference to <code>worker</code>.</li>
663</ul>
664<p>In a worker, this function will close all servers, wait for the <code>'close'</code> event
665on those servers, and then disconnect the IPC channel.</p>
666<p>In the primary, an internal message is sent to the worker causing it to call
667<code>.disconnect()</code> on itself.</p>
668<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p>
669<p>After a server is closed, it will no longer accept new connections,
670but connections may be accepted by any other listening worker. Existing
671connections will be allowed to close as usual. When no more connections exist,
672see <a href="net.html#event-close"><code>server.close()</code></a>, the IPC channel to the worker will close allowing it
673to die gracefully.</p>
674<p>The above applies <em>only</em> to server connections, client connections are not
675automatically closed by workers, and disconnect does not wait for them to close
676before exiting.</p>
677<p>In a worker, <code>process.disconnect</code> exists, but it is not this function;
678it is <a href="child_process.html#subprocessdisconnect"><code>disconnect()</code></a>.</p>
679<p>Because long living server connections may block workers from disconnecting, it
680may be useful to send a message, so application specific actions may be taken to
681close them. It also may be useful to implement a timeout, killing a worker if
682the <code>'disconnect'</code> event has not been emitted after some time.</p>
683<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
684  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
685  <span class="hljs-keyword">let</span> timeout;
686
687  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> {
688    worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'shutdown'</span>);
689    worker.<span class="hljs-title function_">disconnect</span>();
690    timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
691      worker.<span class="hljs-title function_">kill</span>();
692    }, <span class="hljs-number">2000</span>);
693  });
694
695  worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> {
696    <span class="hljs-built_in">clearTimeout</span>(timeout);
697  });
698
699} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
700  <span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
701  <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> {
702    <span class="hljs-comment">// Connections never end</span>
703  });
704
705  server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
706
707  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> {
708    <span class="hljs-keyword">if</span> (msg === <span class="hljs-string">'shutdown'</span>) {
709      <span class="hljs-comment">// Initiate graceful close of any connections to server</span>
710    }
711  });
712}</code> <button class="copy-button">copy</button></pre>
713<h4><code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#workerexitedafterdisconnect" id="workerexitedafterdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_exitedafterdisconnect"></a></h4>
714<div class="api_metadata">
715<span>Added in: v6.0.0</span>
716</div>
717<ul>
718<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
719</ul>
720<p>This property is <code>true</code> if the worker exited due to <code>.disconnect()</code>.
721If the worker exited any other way, it is <code>false</code>. If the
722worker has not exited, it is <code>undefined</code>.</p>
723<p>The boolean <a href="#workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between
724voluntary and accidental exit, the primary may choose not to respawn a worker
725based on this value.</p>
726<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> {
727  <span class="hljs-keyword">if</span> (worker.<span class="hljs-property">exitedAfterDisconnect</span> === <span class="hljs-literal">true</span>) {
728    <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>);
729  }
730});
731
732<span class="hljs-comment">// kill worker</span>
733worker.<span class="hljs-title function_">kill</span>();</code> <button class="copy-button">copy</button></pre>
734<h4><code>worker.id</code><span><a class="mark" href="#workerid" id="workerid">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_id"></a></h4>
735<div class="api_metadata">
736<span>Added in: v0.8.0</span>
737</div>
738<ul>
739<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
740</ul>
741<p>Each new worker is given its own unique id, this id is stored in the
742<code>id</code>.</p>
743<p>While a worker is alive, this is the key that indexes it in
744<code>cluster.workers</code>.</p>
745<h4><code>worker.isConnected()</code><span><a class="mark" href="#workerisconnected" id="workerisconnected">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_isconnected"></a></h4>
746<div class="api_metadata">
747<span>Added in: v0.11.14</span>
748</div>
749<p>This function returns <code>true</code> if the worker is connected to its primary via its
750IPC channel, <code>false</code> otherwise. A worker is connected to its primary after it
751has been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p>
752<h4><code>worker.isDead()</code><span><a class="mark" href="#workerisdead" id="workerisdead">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_isdead"></a></h4>
753<div class="api_metadata">
754<span>Added in: v0.11.14</span>
755</div>
756<p>This function returns <code>true</code> if the worker's process has terminated (either
757because of exiting or being signaled). Otherwise, it returns <code>false</code>.</p>
758
759<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
760<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
761<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
762<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
763
764<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
765
766<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
767  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
768
769  <span class="hljs-comment">// Fork workers.</span>
770  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
771    cluster.<span class="hljs-title function_">fork</span>();
772  }
773
774  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> {
775    <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>());
776  });
777
778  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> {
779    <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>());
780  });
781} <span class="hljs-keyword">else</span> {
782  <span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span>
783  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
784    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
785    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>);
786    process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>);
787  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
788}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
789<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
790<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
791<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
792
793<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
794  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
795
796  <span class="hljs-comment">// Fork workers.</span>
797  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
798    cluster.<span class="hljs-title function_">fork</span>();
799  }
800
801  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> {
802    <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>());
803  });
804
805  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> {
806    <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>());
807  });
808} <span class="hljs-keyword">else</span> {
809  <span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span>
810  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
811    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
812    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>);
813    process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>);
814  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
815}</code><button class="copy-button">copy</button></pre>
816<h4><code>worker.kill([signal])</code><span><a class="mark" href="#workerkillsignal" id="workerkillsignal">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_kill_signal"></a></h4>
817<div class="api_metadata">
818<span>Added in: v0.9.12</span>
819</div>
820<ul>
821<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the kill signal to send to the worker
822process. <strong>Default:</strong> <code>'SIGTERM'</code></li>
823</ul>
824<p>This function will kill the worker. In the primary worker, it does this by
825disconnecting the <code>worker.process</code>, and once disconnected, killing with
826<code>signal</code>. In the worker, it does it by killing the process with <code>signal</code>.</p>
827<p>The <code>kill()</code> function kills the worker process without waiting for a graceful
828disconnect, it has the same behavior as <code>worker.process.kill()</code>.</p>
829<p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.</p>
830<p>In a worker, <code>process.kill()</code> exists, but it is not this function;
831it is <a href="process.html#processkillpid-signal"><code>kill()</code></a>.</p>
832<h4><code>worker.process</code><span><a class="mark" href="#workerprocess" id="workerprocess">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_process"></a></h4>
833<div class="api_metadata">
834<span>Added in: v0.7.0</span>
835</div>
836<ul>
837<li><a href="child_process.html#class-childprocess" class="type">&#x3C;ChildProcess></a></li>
838</ul>
839<p>All workers are created using <a href="child_process.html#child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>, the returned object
840from this function is stored as <code>.process</code>. In a worker, the global <code>process</code>
841is stored.</p>
842<p>See: <a href="child_process.html#child_processforkmodulepath-args-options">Child Process module</a>.</p>
843<p>Workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs
844on <code>process</code> and <code>.exitedAfterDisconnect</code> is not <code>true</code>. This protects against
845accidental disconnection.</p>
846<h4><code>worker.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#workersendmessage-sendhandle-options-callback" id="workersendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_send_message_sendhandle_options_callback"></a></h4>
847<div class="api_metadata">
848<details class="changelog"><summary>History</summary>
849<table>
850<tbody><tr><th>Version</th><th>Changes</th></tr>
851<tr><td>v4.0.0</td>
852<td><p>The <code>callback</code> parameter is supported now.</p></td></tr>
853<tr><td>v0.7.0</td>
854<td><p><span>Added in: v0.7.0</span></p></td></tr>
855</tbody></table>
856</details>
857</div>
858<ul>
859<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
860<li><code>sendHandle</code> <a href="net.html#serverlistenhandle-backlog-callback" class="type">&#x3C;Handle></a></li>
861<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <code>options</code> argument, if present, is an object used to
862parameterize the sending of certain types of handles. <code>options</code> supports
863the following properties:
864<ul>
865<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A value that can be used when passing instances of
866<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
867<strong>Default:</strong> <code>false</code>.</li>
868</ul>
869</li>
870<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
871<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
872</ul>
873<p>Send a message to a worker or primary, optionally with a handle.</p>
874<p>In the primary, this sends a message to a specific worker. It is identical to
875<a href="child_process.html#subprocesssendmessage-sendhandle-options-callback"><code>ChildProcess.send()</code></a>.</p>
876<p>In a worker, this sends a message to the primary. It is identical to
877<code>process.send()</code>.</p>
878<p>This example will echo back all messages from the primary:</p>
879<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
880  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
881  worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'hi there'</span>);
882
883} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
884  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> {
885    process.<span class="hljs-title function_">send</span>(msg);
886  });
887}</code> <button class="copy-button">copy</button></pre>
888</section><section><h3>Event: <code>'disconnect'</code><span><a class="mark" href="#event-disconnect_1" id="event-disconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_disconnect_1"></a></h3>
889<div class="api_metadata">
890<span>Added in: v0.7.9</span>
891</div>
892<ul>
893<li><code>worker</code> <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
894</ul>
895<p>Emitted after the worker IPC channel has disconnected. This can occur when a
896worker exits gracefully, is killed, or is disconnected manually (such as with
897<code>worker.disconnect()</code>).</p>
898<p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These
899events can be used to detect if the process is stuck in a cleanup or if there
900are long-living connections.</p>
901<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> {
902  <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>);
903});</code> <button class="copy-button">copy</button></pre>
904</section><section><h3>Event: <code>'exit'</code><span><a class="mark" href="#event-exit_1" id="event-exit_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_exit_1"></a></h3>
905<div class="api_metadata">
906<span>Added in: v0.7.9</span>
907</div>
908<ul>
909<li><code>worker</code> <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
910<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The exit code, if it exited normally.</li>
911<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused
912the process to be killed.</li>
913</ul>
914<p>When any of the workers die the cluster module will emit the <code>'exit'</code> event.</p>
915<p>This can be used to restart the worker by calling <a href="#clusterforkenv"><code>.fork()</code></a> again.</p>
916<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> {
917  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker %d died (%s). restarting...'</span>,
918              worker.<span class="hljs-property">process</span>.<span class="hljs-property">pid</span>, signal || code);
919  cluster.<span class="hljs-title function_">fork</span>();
920});</code> <button class="copy-button">copy</button></pre>
921<p>See <a href="child_process.html#event-exit"><code>child_process</code> event: <code>'exit'</code></a>.</p>
922</section><section><h3>Event: <code>'fork'</code><span><a class="mark" href="#event-fork" id="event-fork">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_fork"></a></h3>
923<div class="api_metadata">
924<span>Added in: v0.7.0</span>
925</div>
926<ul>
927<li><code>worker</code> <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
928</ul>
929<p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event.
930This can be used to log worker activity, and create a custom timeout.</p>
931<pre><code class="language-js"><span class="hljs-keyword">const</span> timeouts = [];
932<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorMsg</span>(<span class="hljs-params"></span>) {
933  <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>);
934}
935
936cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
937  timeouts[worker.<span class="hljs-property">id</span>] = <span class="hljs-built_in">setTimeout</span>(errorMsg, <span class="hljs-number">2000</span>);
938});
939cluster.<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> {
940  <span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]);
941});
942cluster.<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> {
943  <span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]);
944  <span class="hljs-title function_">errorMsg</span>();
945});</code> <button class="copy-button">copy</button></pre>
946</section><section><h3>Event: <code>'listening'</code><span><a class="mark" href="#event-listening_1" id="event-listening_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_listening_1"></a></h3>
947<div class="api_metadata">
948<span>Added in: v0.7.0</span>
949</div>
950<ul>
951<li><code>worker</code> <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
952<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
953</ul>
954<p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted
955on the server, a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the
956primary.</p>
957<p>The event handler is executed with two arguments, the <code>worker</code> contains the
958worker object and the <code>address</code> object contains the following connection
959properties: <code>address</code>, <code>port</code>, and <code>addressType</code>. This is very useful if the
960worker is listening on more than one address.</p>
961<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> {
962  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
963    <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>);
964});</code> <button class="copy-button">copy</button></pre>
965<p>The <code>addressType</code> is one of:</p>
966<ul>
967<li><code>4</code> (TCPv4)</li>
968<li><code>6</code> (TCPv6)</li>
969<li><code>-1</code> (Unix domain socket)</li>
970<li><code>'udp4'</code> or <code>'udp6'</code> (UDPv4 or UDPv6)</li>
971</ul>
972</section><section><h3>Event: <code>'message'</code><span><a class="mark" href="#event-message_1" id="event-message_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_message_1"></a></h3>
973<div class="api_metadata">
974<details class="changelog"><summary>History</summary>
975<table>
976<tbody><tr><th>Version</th><th>Changes</th></tr>
977<tr><td>v6.0.0</td>
978<td><p>The <code>worker</code> parameter is passed now; see below for details.</p></td></tr>
979<tr><td>v2.5.0</td>
980<td><p><span>Added in: v2.5.0</span></p></td></tr>
981</tbody></table>
982</details>
983</div>
984<ul>
985<li><code>worker</code> <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
986<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
987<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
988</ul>
989<p>Emitted when the cluster primary receives a message from any worker.</p>
990<p>See <a href="child_process.html#event-message"><code>child_process</code> event: <code>'message'</code></a>.</p>
991</section><section><h3>Event: <code>'online'</code><span><a class="mark" href="#event-online_1" id="event-online_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_online_1"></a></h3>
992<div class="api_metadata">
993<span>Added in: v0.7.0</span>
994</div>
995<ul>
996<li><code>worker</code> <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
997</ul>
998<p>After forking a new worker, the worker should respond with an online message.
999When the primary receives an online message it will emit this event.
1000The difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the
1001primary forks a worker, and <code>'online'</code> is emitted when the worker is running.</p>
1002<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> {
1003  <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>);
1004});</code> <button class="copy-button">copy</button></pre>
1005</section><section><h3>Event: <code>'setup'</code><span><a class="mark" href="#event-setup" id="event-setup">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_setup"></a></h3>
1006<div class="api_metadata">
1007<span>Added in: v0.7.1</span>
1008</div>
1009<ul>
1010<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1011</ul>
1012<p>Emitted every time <a href="#clustersetupprimarysettings"><code>.setupPrimary()</code></a> is called.</p>
1013<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time
1014<a href="#clustersetupprimarysettings"><code>.setupPrimary()</code></a> was called and is advisory only, since multiple calls to
1015<a href="#clustersetupprimarysettings"><code>.setupPrimary()</code></a> can be made in a single tick.</p>
1016<p>If accuracy is important, use <code>cluster.settings</code>.</p>
1017</section><section><h3><code>cluster.disconnect([callback])</code><span><a class="mark" href="#clusterdisconnectcallback" id="clusterdisconnectcallback">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_disconnect_callback"></a></h3>
1018<div class="api_metadata">
1019<span>Added in: v0.7.7</span>
1020</div>
1021<ul>
1022<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when all workers are disconnected and handles are
1023closed.</li>
1024</ul>
1025<p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>.</p>
1026<p>When they are disconnected all internal handles will be closed, allowing the
1027primary process to die gracefully if no other event is waiting.</p>
1028<p>The method takes an optional callback argument which will be called when
1029finished.</p>
1030<p>This can only be called from the primary process.</p>
1031</section><section><h3><code>cluster.fork([env])</code><span><a class="mark" href="#clusterforkenv" id="clusterforkenv">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_fork_env"></a></h3>
1032<div class="api_metadata">
1033<span>Added in: v0.6.0</span>
1034</div>
1035<ul>
1036<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Key/value pairs to add to worker process environment.</li>
1037<li>Returns: <a href="cluster.html#class-worker" class="type">&#x3C;cluster.Worker></a></li>
1038</ul>
1039<p>Spawn a new worker process.</p>
1040<p>This can only be called from the primary process.</p>
1041</section><section><h3><code>cluster.isMaster</code><span><a class="mark" href="#clusterismaster" id="clusterismaster">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_ismaster"></a></h3>
1042<div class="api_metadata">
1043<span>Added in: v0.8.1</span><span>Deprecated since: v16.0.0</span>
1044</div>
1045<p></p><div class="api_stability api_stability_0"><a href="documentation.html#stability-index">Stability: 0</a> - Deprecated</div><p></p>
1046<p>Deprecated alias for <a href="#clusterisprimary"><code>cluster.isPrimary</code></a>.</p>
1047</section><section><h3><code>cluster.isPrimary</code><span><a class="mark" href="#clusterisprimary" id="clusterisprimary">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_isprimary"></a></h3>
1048<div class="api_metadata">
1049<span>Added in: v16.0.0</span>
1050</div>
1051<ul>
1052<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
1053</ul>
1054<p>True if the process is a primary. This is determined
1055by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
1056undefined, then <code>isPrimary</code> is <code>true</code>.</p>
1057</section><section><h3><code>cluster.isWorker</code><span><a class="mark" href="#clusterisworker" id="clusterisworker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_isworker"></a></h3>
1058<div class="api_metadata">
1059<span>Added in: v0.6.0</span>
1060</div>
1061<ul>
1062<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
1063</ul>
1064<p>True if the process is not a primary (it is the negation of <code>cluster.isPrimary</code>).</p>
1065</section><section><h3><code>cluster.schedulingPolicy</code><span><a class="mark" href="#clusterschedulingpolicy" id="clusterschedulingpolicy">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_schedulingpolicy"></a></h3>
1066<div class="api_metadata">
1067<span>Added in: v0.11.2</span>
1068</div>
1069<p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or
1070<code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a
1071global setting and effectively frozen once either the first worker is spawned,
1072or <a href="#clustersetupprimarysettings"><code>.setupPrimary()</code></a> is called, whichever comes first.</p>
1073<p><code>SCHED_RR</code> is the default on all operating systems except Windows.
1074Windows will change to <code>SCHED_RR</code> once libuv is able to effectively
1075distribute IOCP handles without incurring a large performance hit.</p>
1076<p><code>cluster.schedulingPolicy</code> can also be set through the
1077<code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid
1078values are <code>'rr'</code> and <code>'none'</code>.</p>
1079</section><section><h3><code>cluster.settings</code><span><a class="mark" href="#clustersettings" id="clustersettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_settings"></a></h3>
1080<div class="api_metadata">
1081<details class="changelog"><summary>History</summary>
1082<table>
1083<tbody><tr><th>Version</th><th>Changes</th></tr>
1084<tr><td>v13.2.0, v12.16.0</td>
1085<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
1086<tr><td>v9.5.0</td>
1087<td><p>The <code>cwd</code> option is supported now.</p></td></tr>
1088<tr><td>v9.4.0</td>
1089<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
1090<tr><td>v8.2.0</td>
1091<td><p>The <code>inspectPort</code> option is supported now.</p></td></tr>
1092<tr><td>v6.4.0</td>
1093<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
1094<tr><td>v0.7.1</td>
1095<td><p><span>Added in: v0.7.1</span></p></td></tr>
1096</tbody></table>
1097</details>
1098</div>
1099<ul>
1100<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1101<ul>
1102<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of string arguments passed to the Node.js
1103executable. <strong>Default:</strong> <code>process.execArgv</code>.</li>
1104<li><code>exec</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> File path to worker file. <strong>Default:</strong> <code>process.argv[1]</code>.</li>
1105<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> String arguments passed to worker.
1106<strong>Default:</strong> <code>process.argv.slice(2)</code>.</li>
1107<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Current working directory of the worker process. <strong>Default:</strong>
1108<code>undefined</code> (inherits from parent process).</li>
1109<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specify the kind of serialization used for sending
1110messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
1111See <a href="child_process.html#advanced-serialization">Advanced serialization for <code>child_process</code></a> for more details.
1112<strong>Default:</strong> <code>false</code>.</li>
1113<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether or not to send output to parent's stdio.
1114<strong>Default:</strong> <code>false</code>.</li>
1115<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> Configures the stdio of forked processes. Because the
1116cluster module relies on IPC to function, this configuration must contain an
1117<code>'ipc'</code> entry. When this option is provided, it overrides <code>silent</code>. See
1118<a href="child_process.html#child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="child_process.html#optionsstdio"><code>stdio</code></a>.</li>
1119<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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>
1120<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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>
1121<li><code>inspectPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Sets inspector port of worker.
1122This can be a number, or a function that takes no arguments and returns a
1123number. By default each worker gets its own port, incremented from the
1124primary's <code>process.debugPort</code>.</li>
1125<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Hide the forked processes console window that would
1126normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
1127</ul>
1128</li>
1129</ul>
1130<p>After calling <a href="#clustersetupprimarysettings"><code>.setupPrimary()</code></a> (or <a href="#clusterforkenv"><code>.fork()</code></a>) this settings object will
1131contain the settings, including the default values.</p>
1132<p>This object is not intended to be changed or set manually.</p>
1133</section><section><h3><code>cluster.setupMaster([settings])</code><span><a class="mark" href="#clustersetupmastersettings" id="clustersetupmastersettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_setupmaster_settings"></a></h3>
1134<div class="api_metadata">
1135<details class="changelog"><summary>History</summary>
1136<table>
1137<tbody><tr><th>Version</th><th>Changes</th></tr>
1138<tr><td>v16.0.0</td>
1139<td><p><span>Deprecated since: v16.0.0</span></p></td></tr>
1140<tr><td>v6.4.0</td>
1141<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
1142<tr><td>v0.7.1</td>
1143<td><p><span>Added in: v0.7.1</span></p></td></tr>
1144</tbody></table>
1145</details>
1146</div>
1147<p></p><div class="api_stability api_stability_0"><a href="documentation.html#stability-index">Stability: 0</a> - Deprecated</div><p></p>
1148<p>Deprecated alias for <a href="#clustersetupprimarysettings"><code>.setupPrimary()</code></a>.</p>
1149</section><section><h3><code>cluster.setupPrimary([settings])</code><span><a class="mark" href="#clustersetupprimarysettings" id="clustersetupprimarysettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_setupprimary_settings"></a></h3>
1150<div class="api_metadata">
1151<span>Added in: v16.0.0</span>
1152</div>
1153<ul>
1154<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> See <a href="#clustersettings"><code>cluster.settings</code></a>.</li>
1155</ul>
1156<p><code>setupPrimary</code> is used to change the default 'fork' behavior. Once called,
1157the settings will be present in <code>cluster.settings</code>.</p>
1158<p>Any settings changes only affect future calls to <a href="#clusterforkenv"><code>.fork()</code></a> and have no
1159effect on workers that are already running.</p>
1160<p>The only attribute of a worker that cannot be set via <code>.setupPrimary()</code> is
1161the <code>env</code> passed to <a href="#clusterforkenv"><code>.fork()</code></a>.</p>
1162<p>The defaults above apply to the first call only; the defaults for later
1163calls are the current values at the time of <code>cluster.setupPrimary()</code> is called.</p>
1164
1165<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
1166
1167cluster.<span class="hljs-title function_">setupPrimary</span>({
1168  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
1169  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>],
1170  <span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span>,
1171});
1172cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span>
1173cluster.<span class="hljs-title function_">setupPrimary</span>({
1174  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
1175  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>],
1176});
1177cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
1178
1179cluster.<span class="hljs-title function_">setupPrimary</span>({
1180  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
1181  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>],
1182  <span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span>,
1183});
1184cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span>
1185cluster.<span class="hljs-title function_">setupPrimary</span>({
1186  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
1187  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>],
1188});
1189cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code><button class="copy-button">copy</button></pre>
1190<p>This can only be called from the primary process.</p>
1191</section><section><h3><code>cluster.worker</code><span><a class="mark" href="#clusterworker" id="clusterworker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_worker"></a></h3>
1192<div class="api_metadata">
1193<span>Added in: v0.7.0</span>
1194</div>
1195<ul>
1196<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1197</ul>
1198<p>A reference to the current worker object. Not available in the primary process.</p>
1199
1200<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
1201
1202<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
1203  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am primary'</span>);
1204  cluster.<span class="hljs-title function_">fork</span>();
1205  cluster.<span class="hljs-title function_">fork</span>();
1206} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
1207  <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>);
1208}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
1209
1210<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
1211  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am primary'</span>);
1212  cluster.<span class="hljs-title function_">fork</span>();
1213  cluster.<span class="hljs-title function_">fork</span>();
1214} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
1215  <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>);
1216}</code><button class="copy-button">copy</button></pre>
1217</section><section><h3><code>cluster.workers</code><span><a class="mark" href="#clusterworkers" id="clusterworkers">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_workers"></a></h3>
1218<div class="api_metadata">
1219<span>Added in: v0.7.0</span>
1220</div>
1221<ul>
1222<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1223</ul>
1224<p>A hash that stores the active worker objects, keyed by <code>id</code> field. This makes it
1225easy to loop through all the workers. It is only available in the primary
1226process.</p>
1227<p>A worker is removed from <code>cluster.workers</code> after the worker has disconnected
1228<em>and</em> exited. The order between these two events cannot be determined in
1229advance. However, it is guaranteed that the removal from the <code>cluster.workers</code>
1230list happens before the last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>
1231
1232<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
1233
1234<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(cluster.<span class="hljs-property">workers</span>)) {
1235  worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>);
1236}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
1237
1238<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(cluster.<span class="hljs-property">workers</span>)) {
1239  worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>);
1240}</code><button class="copy-button">copy</button></pre></section>
1241        <!-- API END -->
1242      </div>
1243    </div>
1244  </div>
1245</body>
1246</html>
1247