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