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>Worker threads | 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/worker_threads.html"> 12 <script async defer src="assets/api.js" type="text/javascript"></script> 13 <style>@media(max-width:326px){.with-13-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style> 14</head> 15<body class="alt apidoc" id="api-section-worker_threads"> 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">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 active">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="worker_threads" 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="#worker-threads">Worker threads</a></span> 124<ul> 125<li><a href="#workergetenvironmentdatakey"><code>worker.getEnvironmentData(key)</code></a></li> 126<li><a href="#workerismainthread"><code>worker.isMainThread</code></a></li> 127<li><a href="#workermarkasuntransferableobject"><code>worker.markAsUntransferable(object)</code></a></li> 128<li><a href="#workermovemessageporttocontextport-contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li> 129<li><a href="#workerparentport"><code>worker.parentPort</code></a></li> 130<li><a href="#workerreceivemessageonportport"><code>worker.receiveMessageOnPort(port)</code></a></li> 131<li><a href="#workerresourcelimits"><code>worker.resourceLimits</code></a></li> 132<li><a href="#workershare_env"><code>worker.SHARE_ENV</code></a></li> 133<li><a href="#workersetenvironmentdatakey-value"><code>worker.setEnvironmentData(key[, value])</code></a></li> 134<li><a href="#workerthreadid"><code>worker.threadId</code></a></li> 135<li><a href="#workerworkerdata"><code>worker.workerData</code></a></li> 136<li><a href="#class-broadcastchannel-extends-eventtarget">Class: <code>BroadcastChannel extends EventTarget</code></a> 137<ul> 138<li><a href="#new-broadcastchannelname"><code>new BroadcastChannel(name)</code></a></li> 139<li><a href="#broadcastchannelclose"><code>broadcastChannel.close()</code></a></li> 140<li><a href="#broadcastchannelonmessage"><code>broadcastChannel.onmessage</code></a></li> 141<li><a href="#broadcastchannelonmessageerror"><code>broadcastChannel.onmessageerror</code></a></li> 142<li><a href="#broadcastchannelpostmessagemessage"><code>broadcastChannel.postMessage(message)</code></a></li> 143<li><a href="#broadcastchannelref"><code>broadcastChannel.ref()</code></a></li> 144<li><a href="#broadcastchannelunref"><code>broadcastChannel.unref()</code></a></li> 145</ul> 146</li> 147<li><a href="#class-messagechannel">Class: <code>MessageChannel</code></a></li> 148<li><a href="#class-messageport">Class: <code>MessagePort</code></a> 149<ul> 150<li><a href="#event-close">Event: <code>'close'</code></a></li> 151<li><a href="#event-message">Event: <code>'message'</code></a></li> 152<li><a href="#event-messageerror">Event: <code>'messageerror'</code></a></li> 153<li><a href="#portclose"><code>port.close()</code></a></li> 154<li><a href="#portpostmessagevalue-transferlist"><code>port.postMessage(value[, transferList])</code></a> 155<ul> 156<li><a href="#considerations-when-transferring-typedarrays-and-buffers">Considerations when transferring TypedArrays and Buffers</a></li> 157<li><a href="#considerations-when-cloning-objects-with-prototypes-classes-and-accessors">Considerations when cloning objects with prototypes, classes, and accessors</a></li> 158</ul> 159</li> 160<li><span class="stability_1"><a href="#porthasref"><code>port.hasRef()</code></a></span></li> 161<li><a href="#portref"><code>port.ref()</code></a></li> 162<li><a href="#portstart"><code>port.start()</code></a></li> 163<li><a href="#portunref"><code>port.unref()</code></a></li> 164</ul> 165</li> 166<li><a href="#class-worker">Class: <code>Worker</code></a> 167<ul> 168<li><a href="#new-workerfilename-options"><code>new Worker(filename[, options])</code></a></li> 169<li><a href="#event-error">Event: <code>'error'</code></a></li> 170<li><a href="#event-exit">Event: <code>'exit'</code></a></li> 171<li><a href="#event-message_1">Event: <code>'message'</code></a></li> 172<li><a href="#event-messageerror_1">Event: <code>'messageerror'</code></a></li> 173<li><a href="#event-online">Event: <code>'online'</code></a></li> 174<li><a href="#workergetheapsnapshot"><code>worker.getHeapSnapshot()</code></a></li> 175<li><a href="#workerperformance"><code>worker.performance</code></a> 176<ul> 177<li><a href="#performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li> 178</ul> 179</li> 180<li><a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage(value[, transferList])</code></a></li> 181<li><a href="#workerref"><code>worker.ref()</code></a></li> 182<li><a href="#workerresourcelimits_1"><code>worker.resourceLimits</code></a></li> 183<li><a href="#workerstderr"><code>worker.stderr</code></a></li> 184<li><a href="#workerstdin"><code>worker.stdin</code></a></li> 185<li><a href="#workerstdout"><code>worker.stdout</code></a></li> 186<li><a href="#workerterminate"><code>worker.terminate()</code></a></li> 187<li><a href="#workerthreadid_1"><code>worker.threadId</code></a></li> 188<li><a href="#workerunref"><code>worker.unref()</code></a></li> 189</ul> 190</li> 191<li><a href="#notes">Notes</a> 192<ul> 193<li><a href="#synchronous-blocking-of-stdio">Synchronous blocking of stdio</a></li> 194<li><a href="#launching-worker-threads-from-preload-scripts">Launching worker threads from preload scripts</a></li> 195</ul> 196</li> 197</ul> 198</li> 199</ul></div></div> 200 </li> 201 202 203 <li class="picker-header"> 204 <a href="#"> 205 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 206 Index 207 </a> 208 209 <div class="picker"><ul> 210<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 211<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 212 213 <li> 214 <a href="index.html">Index</a> 215 </li> 216 </ul> 217 218<hr class="line"> 219<ul> 220<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 221<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> 222<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 223<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 224<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 225<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 226<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 227<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 228<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 229<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 230<li><a href="console.html" class="nav-console">Console</a></li> 231<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 232<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 233<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 234<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 235<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 236<li><a href="dns.html" class="nav-dns">DNS</a></li> 237<li><a href="domain.html" class="nav-domain">Domain</a></li> 238<li><a href="errors.html" class="nav-errors">Errors</a></li> 239<li><a href="events.html" class="nav-events">Events</a></li> 240<li><a href="fs.html" class="nav-fs">File system</a></li> 241<li><a href="globals.html" class="nav-globals">Globals</a></li> 242<li><a href="http.html" class="nav-http">HTTP</a></li> 243<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 244<li><a href="https.html" class="nav-https">HTTPS</a></li> 245<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 246<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 247<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 248<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 249<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> 250<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 251<li><a href="net.html" class="nav-net">Net</a></li> 252<li><a href="os.html" class="nav-os">OS</a></li> 253<li><a href="path.html" class="nav-path">Path</a></li> 254<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 255<li><a href="permissions.html" class="nav-permissions">Permissions</a></li> 256<li><a href="process.html" class="nav-process">Process</a></li> 257<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 258<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 259<li><a href="readline.html" class="nav-readline">Readline</a></li> 260<li><a href="repl.html" class="nav-repl">REPL</a></li> 261<li><a href="report.html" class="nav-report">Report</a></li> 262<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> 263<li><a href="stream.html" class="nav-stream">Stream</a></li> 264<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 265<li><a href="test.html" class="nav-test">Test runner</a></li> 266<li><a href="timers.html" class="nav-timers">Timers</a></li> 267<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 268<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 269<li><a href="tty.html" class="nav-tty">TTY</a></li> 270<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 271<li><a href="url.html" class="nav-url">URL</a></li> 272<li><a href="util.html" class="nav-util">Utilities</a></li> 273<li><a href="v8.html" class="nav-v8">V8</a></li> 274<li><a href="vm.html" class="nav-vm">VM</a></li> 275<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 276<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> 277<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> 278<li><a href="worker_threads.html" class="nav-worker_threads active">Worker threads</a></li> 279<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 280</ul> 281<hr class="line"> 282<ul> 283<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 284</ul></div> 285 </li> 286 287 288 <li class="picker-header"> 289 <a href="#"> 290 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 291 Other versions 292 </a> 293 <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v20.x/api/worker_threads.html">20.x</a></li> 294<li><a href="https://nodejs.org/docs/latest-v19.x/api/worker_threads.html">19.x</a></li> 295<li><a href="https://nodejs.org/docs/latest-v18.x/api/worker_threads.html">18.x <b>LTS</b></a></li> 296<li><a href="https://nodejs.org/docs/latest-v17.x/api/worker_threads.html">17.x</a></li> 297<li><a href="https://nodejs.org/docs/latest-v16.x/api/worker_threads.html">16.x</a></li> 298<li><a href="https://nodejs.org/docs/latest-v15.x/api/worker_threads.html">15.x</a></li> 299<li><a href="https://nodejs.org/docs/latest-v14.x/api/worker_threads.html">14.x</a></li> 300<li><a href="https://nodejs.org/docs/latest-v13.x/api/worker_threads.html">13.x</a></li> 301<li><a href="https://nodejs.org/docs/latest-v12.x/api/worker_threads.html">12.x</a></li> 302<li><a href="https://nodejs.org/docs/latest-v11.x/api/worker_threads.html">11.x</a></li> 303<li><a href="https://nodejs.org/docs/latest-v10.x/api/worker_threads.html">10.x</a></li></ol></div> 304 </li> 305 306 <li class="picker-header"> 307 <a href="#"> 308 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 309 Options 310 </a> 311 312 <div class="picker"> 313 <ul> 314 <li> 315 <a href="all.html">View on single page</a> 316 </li> 317 <li> 318 <a href="worker_threads.json">View as JSON</a> 319 </li> 320 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/worker_threads.md">Edit on GitHub</a></li> 321 </ul> 322 </div> 323 </li> 324 </ul> 325 </div> 326 <hr> 327 </header> 328 329 <details id="toc" open><summary>Table of contents</summary><ul> 330<li><span class="stability_2"><a href="#worker-threads">Worker threads</a></span> 331<ul> 332<li><a href="#workergetenvironmentdatakey"><code>worker.getEnvironmentData(key)</code></a></li> 333<li><a href="#workerismainthread"><code>worker.isMainThread</code></a></li> 334<li><a href="#workermarkasuntransferableobject"><code>worker.markAsUntransferable(object)</code></a></li> 335<li><a href="#workermovemessageporttocontextport-contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li> 336<li><a href="#workerparentport"><code>worker.parentPort</code></a></li> 337<li><a href="#workerreceivemessageonportport"><code>worker.receiveMessageOnPort(port)</code></a></li> 338<li><a href="#workerresourcelimits"><code>worker.resourceLimits</code></a></li> 339<li><a href="#workershare_env"><code>worker.SHARE_ENV</code></a></li> 340<li><a href="#workersetenvironmentdatakey-value"><code>worker.setEnvironmentData(key[, value])</code></a></li> 341<li><a href="#workerthreadid"><code>worker.threadId</code></a></li> 342<li><a href="#workerworkerdata"><code>worker.workerData</code></a></li> 343<li><a href="#class-broadcastchannel-extends-eventtarget">Class: <code>BroadcastChannel extends EventTarget</code></a> 344<ul> 345<li><a href="#new-broadcastchannelname"><code>new BroadcastChannel(name)</code></a></li> 346<li><a href="#broadcastchannelclose"><code>broadcastChannel.close()</code></a></li> 347<li><a href="#broadcastchannelonmessage"><code>broadcastChannel.onmessage</code></a></li> 348<li><a href="#broadcastchannelonmessageerror"><code>broadcastChannel.onmessageerror</code></a></li> 349<li><a href="#broadcastchannelpostmessagemessage"><code>broadcastChannel.postMessage(message)</code></a></li> 350<li><a href="#broadcastchannelref"><code>broadcastChannel.ref()</code></a></li> 351<li><a href="#broadcastchannelunref"><code>broadcastChannel.unref()</code></a></li> 352</ul> 353</li> 354<li><a href="#class-messagechannel">Class: <code>MessageChannel</code></a></li> 355<li><a href="#class-messageport">Class: <code>MessagePort</code></a> 356<ul> 357<li><a href="#event-close">Event: <code>'close'</code></a></li> 358<li><a href="#event-message">Event: <code>'message'</code></a></li> 359<li><a href="#event-messageerror">Event: <code>'messageerror'</code></a></li> 360<li><a href="#portclose"><code>port.close()</code></a></li> 361<li><a href="#portpostmessagevalue-transferlist"><code>port.postMessage(value[, transferList])</code></a> 362<ul> 363<li><a href="#considerations-when-transferring-typedarrays-and-buffers">Considerations when transferring TypedArrays and Buffers</a></li> 364<li><a href="#considerations-when-cloning-objects-with-prototypes-classes-and-accessors">Considerations when cloning objects with prototypes, classes, and accessors</a></li> 365</ul> 366</li> 367<li><span class="stability_1"><a href="#porthasref"><code>port.hasRef()</code></a></span></li> 368<li><a href="#portref"><code>port.ref()</code></a></li> 369<li><a href="#portstart"><code>port.start()</code></a></li> 370<li><a href="#portunref"><code>port.unref()</code></a></li> 371</ul> 372</li> 373<li><a href="#class-worker">Class: <code>Worker</code></a> 374<ul> 375<li><a href="#new-workerfilename-options"><code>new Worker(filename[, options])</code></a></li> 376<li><a href="#event-error">Event: <code>'error'</code></a></li> 377<li><a href="#event-exit">Event: <code>'exit'</code></a></li> 378<li><a href="#event-message_1">Event: <code>'message'</code></a></li> 379<li><a href="#event-messageerror_1">Event: <code>'messageerror'</code></a></li> 380<li><a href="#event-online">Event: <code>'online'</code></a></li> 381<li><a href="#workergetheapsnapshot"><code>worker.getHeapSnapshot()</code></a></li> 382<li><a href="#workerperformance"><code>worker.performance</code></a> 383<ul> 384<li><a href="#performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li> 385</ul> 386</li> 387<li><a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage(value[, transferList])</code></a></li> 388<li><a href="#workerref"><code>worker.ref()</code></a></li> 389<li><a href="#workerresourcelimits_1"><code>worker.resourceLimits</code></a></li> 390<li><a href="#workerstderr"><code>worker.stderr</code></a></li> 391<li><a href="#workerstdin"><code>worker.stdin</code></a></li> 392<li><a href="#workerstdout"><code>worker.stdout</code></a></li> 393<li><a href="#workerterminate"><code>worker.terminate()</code></a></li> 394<li><a href="#workerthreadid_1"><code>worker.threadId</code></a></li> 395<li><a href="#workerunref"><code>worker.unref()</code></a></li> 396</ul> 397</li> 398<li><a href="#notes">Notes</a> 399<ul> 400<li><a href="#synchronous-blocking-of-stdio">Synchronous blocking of stdio</a></li> 401<li><a href="#launching-worker-threads-from-preload-scripts">Launching worker threads from preload scripts</a></li> 402</ul> 403</li> 404</ul> 405</li> 406</ul></details> 407 408 <div id="apicontent"> 409 <h2>Worker threads<span><a class="mark" href="#worker-threads" id="worker-threads">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threads"></a></h2> 410 411<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p> 412<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v18.18.2/lib/worker_threads.js">lib/worker_threads.js</a></p> 413<p>The <code>node:worker_threads</code> module enables the use of threads that execute 414JavaScript in parallel. To access it:</p> 415<pre><code class="language-js"><span class="hljs-keyword">const</span> worker = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);</code> <button class="copy-button">copy</button></pre> 416<p>Workers (threads) are useful for performing CPU-intensive JavaScript operations. 417They do not help much with I/O-intensive work. The Node.js built-in 418asynchronous I/O operations are more efficient than Workers can be.</p> 419<p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do 420so by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code> 421instances.</p> 422<pre><code class="language-js"><span class="hljs-keyword">const</span> { 423 <span class="hljs-title class_">Worker</span>, isMainThread, parentPort, workerData, 424} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 425 426<span class="hljs-keyword">if</span> (isMainThread) { 427 <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">parseJSAsync</span>(<span class="hljs-params">script</span>) { 428 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> { 429 <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, { 430 <span class="hljs-attr">workerData</span>: script, 431 }); 432 worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, resolve); 433 worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, reject); 434 worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> { 435 <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) 436 <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Worker stopped with exit code <span class="hljs-subst">${code}</span>`</span>)); 437 }); 438 }); 439 }; 440} <span class="hljs-keyword">else</span> { 441 <span class="hljs-keyword">const</span> { parse } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-js-parsing-library'</span>); 442 <span class="hljs-keyword">const</span> script = workerData; 443 parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">parse</span>(script)); 444}</code> <button class="copy-button">copy</button></pre> 445<p>The above example spawns a Worker thread for each <code>parseJSAsync()</code> call. In 446practice, use a pool of Workers for these kinds of tasks. Otherwise, the 447overhead of creating Workers would likely exceed their benefit.</p> 448<p>When implementing a worker pool, use the <a href="async_hooks.html#class-asyncresource"><code>AsyncResource</code></a> API to inform 449diagnostic tools (e.g. to provide asynchronous stack traces) about the 450correlation between tasks and their outcomes. See 451<a href="async_context.html#using-asyncresource-for-a-worker-thread-pool">"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool"</a> 452in the <code>async_hooks</code> documentation for an example implementation.</p> 453<p>Worker threads inherit non-process-specific options by default. Refer to 454<a href="#new-workerfilename-options"><code>Worker constructor options</code></a> to know how to customize worker thread options, 455specifically <code>argv</code> and <code>execArgv</code> options.</p> 456<section><h3><code>worker.getEnvironmentData(key)</code><span><a class="mark" href="#workergetenvironmentdatakey" id="workergetenvironmentdatakey">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getenvironmentdata_key"></a></h3> 457<div class="api_metadata"> 458<details class="changelog"><summary>History</summary> 459<table> 460<tbody><tr><th>Version</th><th>Changes</th></tr> 461<tr><td>v17.5.0</td> 462<td><p>No longer experimental.</p></td></tr> 463<tr><td>v15.12.0, v14.18.0</td> 464<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr> 465</tbody></table> 466</details> 467</div> 468<ul> 469<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value that can be used as a 470<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a> key.</li> 471<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> 472</ul> 473<p>Within a worker thread, <code>worker.getEnvironmentData()</code> returns a clone 474of data passed to the spawning thread's <code>worker.setEnvironmentData()</code>. 475Every new <code>Worker</code> receives its own copy of the environment data 476automatically.</p> 477<pre><code class="language-js"><span class="hljs-keyword">const</span> { 478 <span class="hljs-title class_">Worker</span>, 479 isMainThread, 480 setEnvironmentData, 481 getEnvironmentData, 482} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 483 484<span class="hljs-keyword">if</span> (isMainThread) { 485 <span class="hljs-title function_">setEnvironmentData</span>(<span class="hljs-string">'Hello'</span>, <span class="hljs-string">'World!'</span>); 486 <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 487} <span class="hljs-keyword">else</span> { 488 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnvironmentData</span>(<span class="hljs-string">'Hello'</span>)); <span class="hljs-comment">// Prints 'World!'.</span> 489}</code> <button class="copy-button">copy</button></pre> 490</section><section><h3><code>worker.isMainThread</code><span><a class="mark" href="#workerismainthread" id="workerismainthread">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ismainthread"></a></h3> 491<div class="api_metadata"> 492<span>Added in: v10.5.0</span> 493</div> 494<ul> 495<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 496</ul> 497<p>Is <code>true</code> if this code is not running inside of a <a href="#class-worker"><code>Worker</code></a> thread.</p> 498<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 499 500<span class="hljs-keyword">if</span> (isMainThread) { 501 <span class="hljs-comment">// This re-loads the current file inside a Worker instance.</span> 502 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 503} <span class="hljs-keyword">else</span> { 504 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Inside Worker!'</span>); 505 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isMainThread); <span class="hljs-comment">// Prints 'false'.</span> 506}</code> <button class="copy-button">copy</button></pre> 507</section><section><h3><code>worker.markAsUntransferable(object)</code><span><a class="mark" href="#workermarkasuntransferableobject" id="workermarkasuntransferableobject">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_markasuntransferable_object"></a></h3> 508<div class="api_metadata"> 509<span>Added in: v14.5.0, v12.19.0</span> 510</div> 511<p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of 512a <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> call, it is ignored.</p> 513<p>In particular, this makes sense for objects that can be cloned, rather than 514transferred, and which are used by other objects on the sending side. 515For example, Node.js marks the <code>ArrayBuffer</code>s it uses for its 516<a href="buffer.html#static-method-bufferallocunsafesize"><code>Buffer</code> pool</a> with this.</p> 517<p>This operation cannot be undone.</p> 518<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, markAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 519 520<span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">8</span>); 521<span class="hljs-keyword">const</span> typedArray1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(pooledBuffer); 522<span class="hljs-keyword">const</span> typedArray2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>(pooledBuffer); 523 524<span class="hljs-title function_">markAsUntransferable</span>(pooledBuffer); 525 526<span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 527port1.<span class="hljs-title function_">postMessage</span>(typedArray1, [ typedArray1.<span class="hljs-property">buffer</span> ]); 528 529<span class="hljs-comment">// The following line prints the contents of typedArray1 -- it still owns</span> 530<span class="hljs-comment">// its memory and has been cloned, not transferred. Without</span> 531<span class="hljs-comment">// `markAsUntransferable()`, this would print an empty Uint8Array.</span> 532<span class="hljs-comment">// typedArray2 is intact as well.</span> 533<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray1); 534<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray2);</code> <button class="copy-button">copy</button></pre> 535<p>There is no equivalent to this API in browsers.</p> 536</section><section><h3><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code><span><a class="mark" href="#workermovemessageporttocontextport-contextifiedsandbox" id="workermovemessageporttocontextport-contextifiedsandbox">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"></a></h3> 537<div class="api_metadata"> 538<span>Added in: v11.13.0</span> 539</div> 540<ul> 541<li> 542<p><code>port</code> <a href="worker_threads.html#class-messageport" class="type"><MessagePort></a> The message port to transfer.</p> 543</li> 544<li> 545<p><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="vm.html#what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the 546<code>vm.createContext()</code> method.</p> 547</li> 548<li> 549<p>Returns: <a href="worker_threads.html#class-messageport" class="type"><MessagePort></a></p> 550</li> 551</ul> 552<p>Transfer a <code>MessagePort</code> to a different <a href="vm.html"><code>vm</code></a> Context. The original <code>port</code> 553object is rendered unusable, and the returned <code>MessagePort</code> instance 554takes its place.</p> 555<p>The returned <code>MessagePort</code> is an object in the target context and 556inherits from its global <code>Object</code> class. Objects passed to the 557<a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> listener are also created in the target context 558and inherit from its global <code>Object</code> class.</p> 559<p>However, the created <code>MessagePort</code> no longer inherits from 560<a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</code></a>, and only <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> can be used to receive 561events using it.</p> 562</section><section><h3><code>worker.parentPort</code><span><a class="mark" href="#workerparentport" id="workerparentport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_parentport"></a></h3> 563<div class="api_metadata"> 564<span>Added in: v10.5.0</span> 565</div> 566<ul> 567<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="worker_threads.html#class-messageport" class="type"><MessagePort></a></li> 568</ul> 569<p>If this thread is a <a href="#class-worker"><code>Worker</code></a>, this is a <a href="#class-messageport"><code>MessagePort</code></a> 570allowing communication with the parent thread. Messages sent using 571<code>parentPort.postMessage()</code> are available in the parent thread 572using <code>worker.on('message')</code>, and messages sent from the parent thread 573using <code>worker.postMessage()</code> are available in this thread using 574<code>parentPort.on('message')</code>.</p> 575<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 576 577<span class="hljs-keyword">if</span> (isMainThread) { 578 <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 579 worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> { 580 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message); <span class="hljs-comment">// Prints 'Hello, world!'.</span> 581 }); 582 worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'Hello, world!'</span>); 583} <span class="hljs-keyword">else</span> { 584 <span class="hljs-comment">// When a message from the parent thread is received, send it back:</span> 585 parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> { 586 parentPort.<span class="hljs-title function_">postMessage</span>(message); 587 }); 588}</code> <button class="copy-button">copy</button></pre> 589</section><section><h3><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#workerreceivemessageonportport" id="workerreceivemessageonportport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_receivemessageonport_port"></a></h3> 590<div class="api_metadata"> 591<details class="changelog"><summary>History</summary> 592<table> 593<tbody><tr><th>Version</th><th>Changes</th></tr> 594<tr><td>v15.12.0</td> 595<td><p>The port argument can also refer to a <code>BroadcastChannel</code> now.</p></td></tr> 596<tr><td>v12.3.0</td> 597<td><p><span>Added in: v12.3.0</span></p></td></tr> 598</tbody></table> 599</details> 600</div> 601<ul> 602<li> 603<p><code>port</code> <a href="worker_threads.html#class-messageport" class="type"><MessagePort></a> | <a href="worker_threads.html#class-broadcastchannel-extends-eventtarget" class="type"><BroadcastChannel></a></p> 604</li> 605<li> 606<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></p> 607</li> 608</ul> 609<p>Receive a single message from a given <code>MessagePort</code>. If no message is available, 610<code>undefined</code> is returned, otherwise an object with a single <code>message</code> property 611that contains the message payload, corresponding to the oldest message in the 612<code>MessagePort</code>'s queue.</p> 613<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, receiveMessageOnPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 614<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 615port1.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> }); 616 617<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2)); 618<span class="hljs-comment">// Prints: { message: { hello: 'world' } }</span> 619<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2)); 620<span class="hljs-comment">// Prints: undefined</span></code> <button class="copy-button">copy</button></pre> 621<p>When this function is used, no <code>'message'</code> event is emitted and the 622<code>onmessage</code> listener is not invoked.</p> 623</section><section><h3><code>worker.resourceLimits</code><span><a class="mark" href="#workerresourcelimits" id="workerresourcelimits">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits"></a></h3> 624<div class="api_metadata"> 625<span>Added in: v13.2.0, v12.16.0</span> 626</div> 627<ul> 628<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 629<ul> 630<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 631<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 632<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 633<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 634</ul> 635</li> 636</ul> 637<p>Provides the set of JS engine resource constraints inside this Worker thread. 638If the <code>resourceLimits</code> option was passed to the <a href="#class-worker"><code>Worker</code></a> constructor, 639this matches its values.</p> 640<p>If this is used in the main thread, its value is an empty object.</p> 641</section><section><h3><code>worker.SHARE_ENV</code><span><a class="mark" href="#workershare_env" id="workershare_env">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_share_env"></a></h3> 642<div class="api_metadata"> 643<span>Added in: v11.14.0</span> 644</div> 645<ul> 646<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> 647</ul> 648<p>A special value that can be passed as the <code>env</code> option of the <a href="#class-worker"><code>Worker</code></a> 649constructor, to indicate that the current thread and the Worker thread should 650share read and write access to the same set of environment variables.</p> 651<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, <span class="hljs-variable constant_">SHARE_ENV</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 652<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-string">'process.env.SET_IN_WORKER = "foo"'</span>, { <span class="hljs-attr">eval</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">env</span>: <span class="hljs-variable constant_">SHARE_ENV</span> }) 653 .<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> { 654 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">SET_IN_WORKER</span>); <span class="hljs-comment">// Prints 'foo'.</span> 655 });</code> <button class="copy-button">copy</button></pre> 656</section><section><h3><code>worker.setEnvironmentData(key[, value])</code><span><a class="mark" href="#workersetenvironmentdatakey-value" id="workersetenvironmentdatakey-value">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_setenvironmentdata_key_value"></a></h3> 657<div class="api_metadata"> 658<details class="changelog"><summary>History</summary> 659<table> 660<tbody><tr><th>Version</th><th>Changes</th></tr> 661<tr><td>v17.5.0</td> 662<td><p>No longer experimental.</p></td></tr> 663<tr><td>v15.12.0, v14.18.0</td> 664<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr> 665</tbody></table> 666</details> 667</div> 668<ul> 669<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value that can be used as a 670<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a> key.</li> 671<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value that will be cloned 672and passed automatically to all new <code>Worker</code> instances. If <code>value</code> is passed 673as <code>undefined</code>, any previously set value for the <code>key</code> will be deleted.</li> 674</ul> 675<p>The <code>worker.setEnvironmentData()</code> API sets the content of 676<code>worker.getEnvironmentData()</code> in the current thread and all new <code>Worker</code> 677instances spawned from the current context.</p> 678</section><section><h3><code>worker.threadId</code><span><a class="mark" href="#workerthreadid" id="workerthreadid">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid"></a></h3> 679<div class="api_metadata"> 680<span>Added in: v10.5.0</span> 681</div> 682<ul> 683<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 684</ul> 685<p>An integer identifier for the current thread. On the corresponding worker object 686(if there is any), it is available as <a href="#workerthreadid_1"><code>worker.threadId</code></a>. 687This value is unique for each <a href="#class-worker"><code>Worker</code></a> instance inside a single process.</p> 688</section><section><h3><code>worker.workerData</code><span><a class="mark" href="#workerworkerdata" id="workerworkerdata">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_workerdata"></a></h3> 689<div class="api_metadata"> 690<span>Added in: v10.5.0</span> 691</div> 692<p>An arbitrary JavaScript value that contains a clone of the data passed 693to this thread's <code>Worker</code> constructor.</p> 694<p>The data is cloned as if using <a href="#portpostmessagevalue-transferlist"><code>postMessage()</code></a>, 695according to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p> 696<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 697 698<span class="hljs-keyword">if</span> (isMainThread) { 699 <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, { <span class="hljs-attr">workerData</span>: <span class="hljs-string">'Hello, world!'</span> }); 700} <span class="hljs-keyword">else</span> { 701 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(workerData); <span class="hljs-comment">// Prints 'Hello, world!'.</span> 702}</code> <button class="copy-button">copy</button></pre> 703</section><section><h3>Class: <code>BroadcastChannel extends EventTarget</code><span><a class="mark" href="#class-broadcastchannel-extends-eventtarget" id="class-broadcastchannel-extends-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_broadcastchannel_extends_eventtarget"></a></h3> 704<div class="api_metadata"> 705<details class="changelog"><summary>History</summary> 706<table> 707<tbody><tr><th>Version</th><th>Changes</th></tr> 708<tr><td>v18.0.0</td> 709<td><p>No longer experimental.</p></td></tr> 710<tr><td>v15.4.0</td> 711<td><p><span>Added in: v15.4.0</span></p></td></tr> 712</tbody></table> 713</details> 714</div> 715<p>Instances of <code>BroadcastChannel</code> allow asynchronous one-to-many communication 716with all other <code>BroadcastChannel</code> instances bound to the same channel name.</p> 717<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>; 718 719<span class="hljs-keyword">const</span> { 720 isMainThread, 721 <span class="hljs-title class_">BroadcastChannel</span>, 722 <span class="hljs-title class_">Worker</span>, 723} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 724 725<span class="hljs-keyword">const</span> bc = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'hello'</span>); 726 727<span class="hljs-keyword">if</span> (isMainThread) { 728 <span class="hljs-keyword">let</span> c = <span class="hljs-number">0</span>; 729 bc.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> { 730 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">data</span>); 731 <span class="hljs-keyword">if</span> (++c === <span class="hljs-number">10</span>) bc.<span class="hljs-title function_">close</span>(); 732 }; 733 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">10</span>; n++) 734 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 735} <span class="hljs-keyword">else</span> { 736 bc.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hello from every worker'</span>); 737 bc.<span class="hljs-title function_">close</span>(); 738}</code> <button class="copy-button">copy</button></pre> 739<h4><code>new BroadcastChannel(name)</code><span><a class="mark" href="#new-broadcastchannelname" id="new-broadcastchannelname">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_broadcastchannel_name"></a></h4> 740<div class="api_metadata"> 741<span>Added in: v15.4.0</span> 742</div> 743<ul> 744<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The name of the channel to connect to. Any JavaScript value 745that can be converted to a string using <code>`${name}`</code> is permitted.</li> 746</ul> 747<h4><code>broadcastChannel.close()</code><span><a class="mark" href="#broadcastchannelclose" id="broadcastchannelclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_close"></a></h4> 748<div class="api_metadata"> 749<span>Added in: v15.4.0</span> 750</div> 751<p>Closes the <code>BroadcastChannel</code> connection.</p> 752<h4><code>broadcastChannel.onmessage</code><span><a class="mark" href="#broadcastchannelonmessage" id="broadcastchannelonmessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessage"></a></h4> 753<div class="api_metadata"> 754<span>Added in: v15.4.0</span> 755</div> 756<ul> 757<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked with a single <code>MessageEvent</code> argument 758when a message is received.</li> 759</ul> 760<h4><code>broadcastChannel.onmessageerror</code><span><a class="mark" href="#broadcastchannelonmessageerror" id="broadcastchannelonmessageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessageerror"></a></h4> 761<div class="api_metadata"> 762<span>Added in: v15.4.0</span> 763</div> 764<ul> 765<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked with a received message cannot be 766deserialized.</li> 767</ul> 768<h4><code>broadcastChannel.postMessage(message)</code><span><a class="mark" href="#broadcastchannelpostmessagemessage" id="broadcastchannelpostmessagemessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_postmessage_message"></a></h4> 769<div class="api_metadata"> 770<span>Added in: v15.4.0</span> 771</div> 772<ul> 773<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any cloneable JavaScript value.</li> 774</ul> 775<h4><code>broadcastChannel.ref()</code><span><a class="mark" href="#broadcastchannelref" id="broadcastchannelref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_ref"></a></h4> 776<div class="api_metadata"> 777<span>Added in: v15.4.0</span> 778</div> 779<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed 780BroadcastChannel does <em>not</em> let the program exit if it's the only active handle 781left (the default behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again 782has no effect.</p> 783<h4><code>broadcastChannel.unref()</code><span><a class="mark" href="#broadcastchannelunref" id="broadcastchannelunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_unref"></a></h4> 784<div class="api_metadata"> 785<span>Added in: v15.4.0</span> 786</div> 787<p>Calling <code>unref()</code> on a BroadcastChannel allows the thread to exit if this 788is the only active handle in the event system. If the BroadcastChannel is 789already <code>unref()</code>ed calling <code>unref()</code> again has no effect.</p> 790</section><section><h3>Class: <code>MessageChannel</code><span><a class="mark" href="#class-messagechannel" id="class-messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messagechannel"></a></h3> 791<div class="api_metadata"> 792<span>Added in: v10.5.0</span> 793</div> 794<p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous, 795two-way communications channel. 796The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code> 797yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked 798<a href="#class-messageport"><code>MessagePort</code></a> instances.</p> 799<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 800 801<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 802port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received'</span>, message)); 803port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> }); 804<span class="hljs-comment">// Prints: received { foo: 'bar' } from the `port1.on('message')` listener</span></code> <button class="copy-button">copy</button></pre> 805</section><section><h3>Class: <code>MessagePort</code><span><a class="mark" href="#class-messageport" id="class-messageport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messageport"></a></h3> 806<div class="api_metadata"> 807<details class="changelog"><summary>History</summary> 808<table> 809<tbody><tr><th>Version</th><th>Changes</th></tr> 810<tr><td>v14.7.0</td> 811<td><p>This class now inherits from <code>EventTarget</code> rather than from <code>EventEmitter</code>.</p></td></tr> 812<tr><td>v10.5.0</td> 813<td><p><span>Added in: v10.5.0</span></p></td></tr> 814</tbody></table> 815</details> 816</div> 817<ul> 818<li>Extends: <a href="events.html#class-eventtarget" class="type"><EventTarget></a></li> 819</ul> 820<p>Instances of the <code>worker.MessagePort</code> class represent one end of an 821asynchronous, two-way communications channel. It can be used to transfer 822structured data, memory regions and other <code>MessagePort</code>s between different 823<a href="#class-worker"><code>Worker</code></a>s.</p> 824<p>This implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p> 825<h4>Event: <code>'close'</code><span><a class="mark" href="#event-close" id="event-close">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_close"></a></h4> 826<div class="api_metadata"> 827<span>Added in: v10.5.0</span> 828</div> 829<p>The <code>'close'</code> event is emitted once either side of the channel has been 830disconnected.</p> 831<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 832<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 833 834<span class="hljs-comment">// Prints:</span> 835<span class="hljs-comment">// foobar</span> 836<span class="hljs-comment">// closed!</span> 837port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message)); 838port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'closed!'</span>)); 839 840port1.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'foobar'</span>); 841port1.<span class="hljs-title function_">close</span>();</code> <button class="copy-button">copy</button></pre> 842<h4>Event: <code>'message'</code><span><a class="mark" href="#event-message" id="event-message">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message"></a></h4> 843<div class="api_metadata"> 844<span>Added in: v10.5.0</span> 845</div> 846<ul> 847<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li> 848</ul> 849<p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned 850input of <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a>.</p> 851<p>Listeners on this event receive a clone of the <code>value</code> parameter as passed 852to <code>postMessage()</code> and no further arguments.</p> 853<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#event-messageerror" id="event-messageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror"></a></h4> 854<div class="api_metadata"> 855<span>Added in: v14.5.0, v12.19.0</span> 856</div> 857<ul> 858<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An Error object</li> 859</ul> 860<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p> 861<p>Currently, this event is emitted when there is an error occurring while 862instantiating the posted JS object on the receiving end. Such situations 863are rare, but can happen, for instance, when certain Node.js API objects 864are received in a <code>vm.Context</code> (where Node.js APIs are currently 865unavailable).</p> 866<h4><code>port.close()</code><span><a class="mark" href="#portclose" id="portclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_close"></a></h4> 867<div class="api_metadata"> 868<span>Added in: v10.5.0</span> 869</div> 870<p>Disables further sending of messages on either side of the connection. 871This method can be called when no further communication will happen over this 872<code>MessagePort</code>.</p> 873<p>The <a href="#event-close"><code>'close'</code> event</a> is emitted on both <code>MessagePort</code> instances that 874are part of the channel.</p> 875<h4><code>port.postMessage(value[, transferList])</code><span><a class="mark" href="#portpostmessagevalue-transferlist" id="portpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_postmessage_value_transferlist"></a></h4> 876<div class="api_metadata"> 877<details class="changelog"><summary>History</summary> 878<table> 879<tbody><tr><th>Version</th><th>Changes</th></tr> 880<tr><td>v15.6.0</td> 881<td><p>Added <code>X509Certificate</code> to the list of cloneable types.</p></td></tr> 882<tr><td>v15.0.0</td> 883<td><p>Added <code>CryptoKey</code> to the list of cloneable types.</p></td></tr> 884<tr><td>v15.14.0, v14.18.0</td> 885<td><p>Add 'BlockList' to the list of cloneable types.</p></td></tr> 886<tr><td>v15.9.0, v14.18.0</td> 887<td><p>Add 'Histogram' types to the list of cloneable types.</p></td></tr> 888<tr><td>v14.5.0, v12.19.0</td> 889<td><p>Added <code>KeyObject</code> to the list of cloneable types.</p></td></tr> 890<tr><td>v14.5.0, v12.19.0</td> 891<td><p>Added <code>FileHandle</code> to the list of transferable types.</p></td></tr> 892<tr><td>v10.5.0</td> 893<td><p><span>Added in: v10.5.0</span></p></td></tr> 894</tbody></table> 895</details> 896</div> 897<ul> 898<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> 899<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> 900</ul> 901<p>Sends a JavaScript value to the receiving side of this channel. 902<code>value</code> is transferred in a way which is compatible with 903the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p> 904<p>In particular, the significant differences to <code>JSON</code> are:</p> 905<ul> 906<li><code>value</code> may contain circular references.</li> 907<li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s, 908<code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li> 909<li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s 910and <code>SharedArrayBuffer</code>s.</li> 911<li><code>value</code> may contain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instances.</li> 912<li><code>value</code> may not contain native (C++-backed) objects other than: 913<ul> 914<li><a href="webcrypto.html#class-cryptokey" class="type"><CryptoKey></a>s,</li> 915<li><a href="fs.html#class-filehandle" class="type"><FileHandle></a>s,</li> 916<li><a href="perf_hooks.html#class-histogram" class="type"><Histogram></a>s,</li> 917<li><a href="crypto.html#class-keyobject" class="type"><KeyObject></a>s,</li> 918<li><a href="worker_threads.html#class-messageport" class="type"><MessagePort></a>s,</li> 919<li><a href="net.html#class-netblocklist" class="type"><net.BlockList></a>s,</li> 920<li><a href="net.html#class-netsocketaddress" class="type"><net.SocketAddress></a>es,</li> 921<li><a href="crypto.html#class-x509certificate" class="type"><X509Certificate></a>s.</li> 922</ul> 923</li> 924</ul> 925<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 926<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 927 928port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message)); 929 930<span class="hljs-keyword">const</span> circularData = {}; 931circularData.<span class="hljs-property">foo</span> = circularData; 932<span class="hljs-comment">// Prints: { foo: [Circular] }</span> 933port2.<span class="hljs-title function_">postMessage</span>(circularData);</code> <button class="copy-button">copy</button></pre> 934<p><code>transferList</code> may be a list of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="#class-messageport"><code>MessagePort</code></a>, and 935<a href="fs.html#class-filehandle"><code>FileHandle</code></a> objects. 936After transferring, they are not usable on the sending side of the channel 937anymore (even if they are not contained in <code>value</code>). Unlike with 938<a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently 939not supported.</p> 940<p>If <code>value</code> contains <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances, those are accessible 941from either thread. They cannot be listed in <code>transferList</code>.</p> 942<p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in 943<code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p> 944<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 945<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 946 947port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message)); 948 949<span class="hljs-keyword">const</span> uint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([ <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span> ]); 950<span class="hljs-comment">// This posts a copy of `uint8Array`:</span> 951port2.<span class="hljs-title function_">postMessage</span>(uint8Array); 952<span class="hljs-comment">// This does not copy data, but renders `uint8Array` unusable:</span> 953port2.<span class="hljs-title function_">postMessage</span>(uint8Array, [ uint8Array.<span class="hljs-property">buffer</span> ]); 954 955<span class="hljs-comment">// The memory for the `sharedUint8Array` is accessible from both the</span> 956<span class="hljs-comment">// original and the copy received by `.on('message')`:</span> 957<span class="hljs-keyword">const</span> sharedUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>(<span class="hljs-number">4</span>)); 958port2.<span class="hljs-title function_">postMessage</span>(sharedUint8Array); 959 960<span class="hljs-comment">// This transfers a freshly created message port to the receiver.</span> 961<span class="hljs-comment">// This can be used, for example, to create communication channels between</span> 962<span class="hljs-comment">// multiple `Worker` threads that are children of the same parent thread.</span> 963<span class="hljs-keyword">const</span> otherChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 964port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">port</span>: otherChannel.<span class="hljs-property">port1</span> }, [ otherChannel.<span class="hljs-property">port1</span> ]);</code> <button class="copy-button">copy</button></pre> 965<p>The message object is cloned immediately, and can be modified after 966posting without having side effects.</p> 967<p>For more information on the serialization and deserialization mechanisms 968behind this API, see the <a href="v8.html#serialization-api">serialization API of the <code>node:v8</code> module</a>.</p> 969<h5>Considerations when transferring TypedArrays and Buffers<span><a class="mark" href="#considerations-when-transferring-typedarrays-and-buffers" id="considerations-when-transferring-typedarrays-and-buffers">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_transferring_typedarrays_and_buffers"></a></h5> 970<p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying 971<code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores 972the raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a 973way of viewing and manipulating the data. It is possible and common 974for multiple views to be created over the same <code>ArrayBuffer</code> instance. 975Great care must be taken when using a transfer list to transfer an 976<code>ArrayBuffer</code> as doing so causes all <code>TypedArray</code> and <code>Buffer</code> 977instances that share that same <code>ArrayBuffer</code> to become unusable.</p> 978<pre><code class="language-js"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>); 979 980<span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(ab); 981<span class="hljs-keyword">const</span> u2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(ab); 982 983<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>); <span class="hljs-comment">// prints 5</span> 984 985port.<span class="hljs-title function_">postMessage</span>(u1, [u1.<span class="hljs-property">buffer</span>]); 986 987<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>); <span class="hljs-comment">// prints 0</span></code> <button class="copy-button">copy</button></pre> 988<p>For <code>Buffer</code> instances, specifically, whether the underlying 989<code>ArrayBuffer</code> can be transferred or cloned depends entirely on how 990instances were created, which often cannot be reliably determined.</p> 991<p>An <code>ArrayBuffer</code> can be marked with <a href="#workermarkasuntransferableobject"><code>markAsUntransferable()</code></a> to indicate 992that it should always be cloned and never transferred.</p> 993<p>Depending on how a <code>Buffer</code> instance was created, it may or may 994not own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not 995be transferred unless it is known that the <code>Buffer</code> instance 996owns it. In particular, for <code>Buffer</code>s created from the internal 997<code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.allocUnsafe()</code>), 998transferring them is not possible and they are always cloned, 999which sends a copy of the entire <code>Buffer</code> pool. 1000This behavior may come with unintended higher memory 1001usage and possible security concerns.</p> 1002<p>See <a href="buffer.html#static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> for more details on <code>Buffer</code> pooling.</p> 1003<p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using 1004<code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be 1005transferred but doing so renders all other existing views of 1006those <code>ArrayBuffer</code>s unusable.</p> 1007<h5>Considerations when cloning objects with prototypes, classes, and accessors<span><a class="mark" href="#considerations-when-cloning-objects-with-prototypes-classes-and-accessors" id="considerations-when-cloning-objects-with-prototypes-classes-and-accessors">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_cloning_objects_with_prototypes_classes_and_accessors"></a></h5> 1008<p>Because object cloning uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, 1009non-enumerable properties, property accessors, and object prototypes are 1010not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as 1011plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s on the receiving side, and instances of JavaScript 1012classes will be cloned as plain JavaScript objects.</p> 1013<pre><code class="language-js"><span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'b'</span>); 1014 1015<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> { 1016 #a = <span class="hljs-number">1</span>; 1017 <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) { 1018 <span class="hljs-variable language_">this</span>[b] = <span class="hljs-number">2</span>; 1019 <span class="hljs-variable language_">this</span>.<span class="hljs-property">c</span> = <span class="hljs-number">3</span>; 1020 } 1021 1022 <span class="hljs-keyword">get</span> <span class="hljs-title function_">d</span>() { <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>; } 1023} 1024 1025<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 1026 1027port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 1028 1029port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>()); 1030 1031<span class="hljs-comment">// Prints: { c: 3 }</span></code> <button class="copy-button">copy</button></pre> 1032<p>This limitation extends to many built-in objects, such as the global <code>URL</code> 1033object:</p> 1034<pre><code class="language-js"><span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 1035 1036port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 1037 1038port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>)); 1039 1040<span class="hljs-comment">// Prints: { }</span></code> <button class="copy-button">copy</button></pre> 1041<h4><code>port.hasRef()</code><span><a class="mark" href="#porthasref" id="porthasref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_hasref"></a></h4> 1042<div class="api_metadata"> 1043<span>Added in: v18.1.0</span> 1044</div> 1045<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1046<ul> 1047<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1048</ul> 1049<p>If true, the <code>MessagePort</code> object will keep the Node.js event loop active.</p> 1050<h4><code>port.ref()</code><span><a class="mark" href="#portref" id="portref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_ref"></a></h4> 1051<div class="api_metadata"> 1052<span>Added in: v10.5.0</span> 1053</div> 1054<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port does 1055<em>not</em> let the program exit if it's the only active handle left (the default 1056behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again has no effect.</p> 1057<p>If listeners are attached or removed using <code>.on('message')</code>, the port 1058is <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether 1059listeners for the event exist.</p> 1060<h4><code>port.start()</code><span><a class="mark" href="#portstart" id="portstart">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_start"></a></h4> 1061<div class="api_metadata"> 1062<span>Added in: v10.5.0</span> 1063</div> 1064<p>Starts receiving messages on this <code>MessagePort</code>. When using this port 1065as an event emitter, this is called automatically once <code>'message'</code> 1066listeners are attached.</p> 1067<p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js, 1068it is only useful for ignoring messages when no event listener is present. 1069Node.js also diverges in its handling of <code>.onmessage</code>. Setting it 1070automatically calls <code>.start()</code>, but unsetting it lets messages queue up 1071until a new handler is set or the port is discarded.</p> 1072<h4><code>port.unref()</code><span><a class="mark" href="#portunref" id="portunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_unref"></a></h4> 1073<div class="api_metadata"> 1074<span>Added in: v10.5.0</span> 1075</div> 1076<p>Calling <code>unref()</code> on a port allows the thread to exit if this is the only 1077active handle in the event system. If the port is already <code>unref()</code>ed calling 1078<code>unref()</code> again has no effect.</p> 1079<p>If listeners are attached or removed using <code>.on('message')</code>, the port is 1080<code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether 1081listeners for the event exist.</p> 1082</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="worker_threads_class_worker"></a></h3> 1083<div class="api_metadata"> 1084<span>Added in: v10.5.0</span> 1085</div> 1086<ul> 1087<li>Extends: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> 1088</ul> 1089<p>The <code>Worker</code> class represents an independent JavaScript execution thread. 1090Most Node.js APIs are available inside of it.</p> 1091<p>Notable differences inside a Worker environment are:</p> 1092<ul> 1093<li>The <a href="process.html#processstdin"><code>process.stdin</code></a>, <a href="process.html#processstdout"><code>process.stdout</code></a>, and <a href="process.html#processstderr"><code>process.stderr</code></a> 1094streams may be redirected by the parent thread.</li> 1095<li>The <a href="#workerismainthread"><code>require('node:worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li> 1096<li>The <a href="#workerparentport"><code>require('node:worker_threads').parentPort</code></a> message port is available.</li> 1097<li><a href="process.html#processexitcode"><code>process.exit()</code></a> does not stop the whole program, just the single thread, 1098and <a href="process.html#processabort"><code>process.abort()</code></a> is not available.</li> 1099<li><a href="process.html#processchdirdirectory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids 1100are not available.</li> 1101<li><a href="process.html#processenv"><code>process.env</code></a> is a copy of the parent thread's environment variables, 1102unless otherwise specified. Changes to one copy are not visible in other 1103threads, and are not visible to native add-ons (unless 1104<a href="#workershare_env"><code>worker.SHARE_ENV</code></a> is passed as the <code>env</code> option to the 1105<a href="#class-worker"><code>Worker</code></a> constructor).</li> 1106<li><a href="process.html#processtitle"><code>process.title</code></a> cannot be modified.</li> 1107<li>Signals are not delivered through <a href="process.html#signal-events"><code>process.on('...')</code></a>.</li> 1108<li>Execution may stop at any point as a result of <a href="#workerterminate"><code>worker.terminate()</code></a> 1109being invoked.</li> 1110<li>IPC channels from parent processes are not accessible.</li> 1111<li>The <a href="tracing.html"><code>trace_events</code></a> module is not supported.</li> 1112<li>Native add-ons can only be loaded from multiple threads if they fulfill 1113<a href="addons.html#worker-support">certain conditions</a>.</li> 1114</ul> 1115<p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p> 1116<p>Like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a> and the <a href="cluster.html"><code>node:cluster</code> module</a>, two-way communication 1117can be achieved through inter-thread message passing. Internally, a <code>Worker</code> has 1118a built-in pair of <a href="#class-messageport"><code>MessagePort</code></a>s that are already associated with each 1119other when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent 1120side is not directly exposed, its functionalities are exposed through 1121<a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage()</code></a> and the <a href="#event-message_1"><code>worker.on('message')</code></a> event 1122on the <code>Worker</code> object for the parent thread.</p> 1123<p>To create custom messaging channels (which is encouraged over using the default 1124global channel because it facilitates separation of concerns), users can create 1125a <code>MessageChannel</code> object on either thread and pass one of the 1126<code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a 1127pre-existing channel, such as the global one.</p> 1128<p>See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed, 1129and what kind of JavaScript values can be successfully transported through 1130the thread barrier.</p> 1131<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>); 1132<span class="hljs-keyword">const</span> { 1133 <span class="hljs-title class_">Worker</span>, <span class="hljs-title class_">MessageChannel</span>, <span class="hljs-title class_">MessagePort</span>, isMainThread, parentPort, 1134} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 1135<span class="hljs-keyword">if</span> (isMainThread) { 1136 <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 1137 <span class="hljs-keyword">const</span> subChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); 1138 worker.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hereIsYourPort</span>: subChannel.<span class="hljs-property">port1</span> }, [subChannel.<span class="hljs-property">port1</span>]); 1139 subChannel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { 1140 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received:'</span>, value); 1141 }); 1142} <span class="hljs-keyword">else</span> { 1143 parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { 1144 <span class="hljs-title function_">assert</span>(value.<span class="hljs-property">hereIsYourPort</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MessagePort</span>); 1145 value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'the worker is sending this'</span>); 1146 value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">close</span>(); 1147 }); 1148}</code> <button class="copy-button">copy</button></pre> 1149<h4><code>new Worker(filename[, options])</code><span><a class="mark" href="#new-workerfilename-options" id="new-workerfilename-options">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_worker_filename_options"></a></h4> 1150<div class="api_metadata"> 1151<details class="changelog"><summary>History</summary> 1152<table> 1153<tbody><tr><th>Version</th><th>Changes</th></tr> 1154<tr><td>v18.16.0</td> 1155<td><p>Added support for a <code>name</code> option, which allows adding a name to worker title for debugging.</p></td></tr> 1156<tr><td>v14.9.0</td> 1157<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>data:</code> protocol.</p></td></tr> 1158<tr><td>v14.9.0</td> 1159<td><p>The <code>trackUnmanagedFds</code> option was set to <code>true</code> by default.</p></td></tr> 1160<tr><td>v14.6.0, v12.19.0</td> 1161<td><p>The <code>trackUnmanagedFds</code> option was introduced.</p></td></tr> 1162<tr><td>v13.13.0, v12.17.0</td> 1163<td><p>The <code>transferList</code> option was introduced.</p></td></tr> 1164<tr><td>v13.12.0, v12.17.0</td> 1165<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr> 1166<tr><td>v13.4.0, v12.16.0</td> 1167<td><p>The <code>argv</code> option was introduced.</p></td></tr> 1168<tr><td>v13.2.0, v12.16.0</td> 1169<td><p>The <code>resourceLimits</code> option was introduced.</p></td></tr> 1170<tr><td>v10.5.0</td> 1171<td><p><span>Added in: v10.5.0</span></p></td></tr> 1172</tbody></table> 1173</details> 1174</div> 1175<ul> 1176<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> The path to the Worker's main script or module. Must 1177be either an absolute path or a relative path (i.e. relative to the 1178current working directory) starting with <code>./</code> or <code>../</code>, or a WHATWG <code>URL</code> 1179object using <code>file:</code> or <code>data:</code> protocol. 1180When using a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URL</a>, the data is interpreted based on MIME type using 1181the <a href="esm.html#data-imports">ECMAScript module loader</a>. 1182If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code 1183rather than a path.</li> 1184<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 1185<ul> 1186<li><code>argv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any[]></a> List of arguments which would be stringified and appended to 1187<code>process.argv</code> in the worker. This is mostly similar to the <code>workerData</code> 1188but the values are available on the global <code>process.argv</code> as if they 1189were passed as CLI options to the script.</li> 1190<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If set, specifies the initial value of <code>process.env</code> inside 1191the Worker thread. As a special value, <a href="#workershare_env"><code>worker.SHARE_ENV</code></a> may be used 1192to specify that the parent thread and the child thread should share their 1193environment variables; in that case, changes to one thread's <code>process.env</code> 1194object affect the other thread as well. <strong>Default:</strong> <code>process.env</code>.</li> 1195<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> and the first argument is a <code>string</code>, interpret 1196the first argument to the constructor as a script that is executed once the 1197worker is online.</li> 1198<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 node CLI options passed to the worker. 1199V8 options (such as <code>--max-old-space-size</code>) and options that affect the 1200process (such as <code>--title</code>) are not supported. If set, this is provided 1201as <a href="process.html#processexecargv"><code>process.execArgv</code></a> inside the worker. By default, options are 1202inherited from the parent thread.</li> 1203<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code> 1204provides a writable stream whose contents appear as <code>process.stdin</code> 1205inside the Worker. By default, no data is provided.</li> 1206<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> is 1207not automatically piped through to <code>process.stdout</code> in the parent.</li> 1208<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> is 1209not automatically piped through to <code>process.stderr</code> in the parent.</li> 1210<li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any JavaScript value that is cloned and made 1211available as <a href="#workerworkerdata"><code>require('node:worker_threads').workerData</code></a>. The cloning 1212occurs as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, and an error 1213is thrown if the object cannot be cloned (e.g. because it contains 1214<code>function</code>s).</li> 1215<li><code>trackUnmanagedFds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then the Worker 1216tracks raw file descriptors managed through <a href="fs.html#fsopenpath-flags-mode-callback"><code>fs.open()</code></a> and 1217<a href="fs.html#fsclosefd-callback"><code>fs.close()</code></a>, and closes them when the Worker exits, similar to other 1218resources like network sockets or file descriptors managed through 1219the <a href="fs.html#class-filehandle"><code>FileHandle</code></a> API. This option is automatically inherited by all 1220nested <code>Worker</code>s. <strong>Default:</strong> <code>true</code>.</li> 1221<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> If one or more <code>MessagePort</code>-like objects 1222are passed in <code>workerData</code>, a <code>transferList</code> is required for those 1223items or <a href="errors.html#err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> is thrown. 1224See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information.</li> 1225<li><code>resourceLimits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An optional set of resource limits for the new JS 1226engine instance. Reaching these limits leads to termination of the <code>Worker</code> 1227instance. These limits only affect the JS engine, and no external data, 1228including no <code>ArrayBuffer</code>s. Even if these limits are set, the process may 1229still abort if it encounters a global out-of-memory situation. 1230<ul> 1231<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum size of the main heap in 1232MB. If the command-line argument <a href="cli.html#--max-old-space-sizesize-in-megabytes"><code>--max-old-space-size</code></a> is set, it 1233overrides this setting.</li> 1234<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum size of a heap space for 1235recently created objects. If the command-line argument 1236<a href="cli.html#--max-semi-space-sizesize-in-megabytes"><code>--max-semi-space-size</code></a> is set, it overrides this setting.</li> 1237<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The size of a pre-allocated memory range 1238used for generated code.</li> 1239<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The default maximum stack size for the thread. 1240Small values may lead to unusable Worker instances. <strong>Default:</strong> <code>4</code>.</li> 1241</ul> 1242</li> 1243<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional <code>name</code> to be appended to the worker title 1244for debugging/identification purposes, making the final title as 1245<code>[worker ${id}] ${name}</code>. <strong>Default:</strong> <code>''</code>.</li> 1246</ul> 1247</li> 1248</ul> 1249<h4>Event: <code>'error'</code><span><a class="mark" href="#event-error" id="event-error">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_error"></a></h4> 1250<div class="api_metadata"> 1251<span>Added in: v10.5.0</span> 1252</div> 1253<ul> 1254<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1255</ul> 1256<p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught 1257exception. In that case, the worker is terminated.</p> 1258<h4>Event: <code>'exit'</code><span><a class="mark" href="#event-exit" id="event-exit">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_exit"></a></h4> 1259<div class="api_metadata"> 1260<span>Added in: v10.5.0</span> 1261</div> 1262<ul> 1263<li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1264</ul> 1265<p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker 1266exited by calling <a href="process.html#processexitcode"><code>process.exit()</code></a>, the <code>exitCode</code> parameter is the 1267passed exit code. If the worker was terminated, the <code>exitCode</code> parameter is 1268<code>1</code>.</p> 1269<p>This is the final event emitted by any <code>Worker</code> instance.</p> 1270<h4>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="worker_threads_event_message_1"></a></h4> 1271<div class="api_metadata"> 1272<span>Added in: v10.5.0</span> 1273</div> 1274<ul> 1275<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li> 1276</ul> 1277<p>The <code>'message'</code> event is emitted when the worker thread has invoked 1278<a href="#workerpostmessagevalue-transferlist"><code>require('node:worker_threads').parentPort.postMessage()</code></a>. 1279See the <a href="#event-message"><code>port.on('message')</code></a> event for more details.</p> 1280<p>All messages sent from the worker thread are emitted before the 1281<a href="#event-exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p> 1282<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#event-messageerror_1" id="event-messageerror_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror_1"></a></h4> 1283<div class="api_metadata"> 1284<span>Added in: v14.5.0, v12.19.0</span> 1285</div> 1286<ul> 1287<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An Error object</li> 1288</ul> 1289<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p> 1290<h4>Event: <code>'online'</code><span><a class="mark" href="#event-online" id="event-online">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_online"></a></h4> 1291<div class="api_metadata"> 1292<span>Added in: v10.5.0</span> 1293</div> 1294<p>The <code>'online'</code> event is emitted when the worker thread has started executing 1295JavaScript code.</p> 1296<h4><code>worker.getHeapSnapshot()</code><span><a class="mark" href="#workergetheapsnapshot" id="workergetheapsnapshot">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getheapsnapshot"></a></h4> 1297<div class="api_metadata"> 1298<span>Added in: v13.9.0, v12.17.0</span> 1299</div> 1300<ul> 1301<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> A promise for a Readable Stream containing 1302a V8 heap snapshot</li> 1303</ul> 1304<p>Returns a readable stream for a V8 snapshot of the current state of the Worker. 1305See <a href="v8.html#v8getheapsnapshot"><code>v8.getHeapSnapshot()</code></a> for more details.</p> 1306<p>If the Worker thread is no longer running, which may occur before the 1307<a href="#event-exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> is rejected 1308immediately with an <a href="errors.html#err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p> 1309<h4><code>worker.performance</code><span><a class="mark" href="#workerperformance" id="workerperformance">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_performance"></a></h4> 1310<div class="api_metadata"> 1311<span>Added in: v15.1.0, v14.17.0, v12.22.0</span> 1312</div> 1313<p>An object that can be used to query performance information from a worker 1314instance. Similar to <a href="perf_hooks.html#perf_hooksperformance"><code>perf_hooks.performance</code></a>.</p> 1315<h5><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#performanceeventlooputilizationutilization1-utilization2" id="performanceeventlooputilizationutilization1-utilization2">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_performance_eventlooputilization_utilization1_utilization2"></a></h5> 1316<div class="api_metadata"> 1317<span>Added in: v15.1.0, v14.17.0, v12.22.0</span> 1318</div> 1319<ul> 1320<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to 1321<code>eventLoopUtilization()</code>.</li> 1322<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to 1323<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</li> 1324<li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 1325<ul> 1326<li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1327<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1328<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1329</ul> 1330</li> 1331</ul> 1332<p>The same call as <a href="perf_hooks.html#performanceeventlooputilizationutilization1-utilization2"><code>perf_hooks</code> <code>eventLoopUtilization()</code></a>, except the values 1333of the worker instance are returned.</p> 1334<p>One difference is that, unlike the main thread, bootstrapping within a worker 1335is done within the event loop. So the event loop utilization is 1336immediately available once the worker's script begins execution.</p> 1337<p>An <code>idle</code> time that does not increase does not indicate that the worker is 1338stuck in bootstrap. The following examples shows how the worker's entire 1339lifetime never accumulates any <code>idle</code> time, but is still be able to process 1340messages.</p> 1341<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 1342 1343<span class="hljs-keyword">if</span> (isMainThread) { 1344 <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 1345 <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> { 1346 worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hi'</span>); 1347 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(worker.<span class="hljs-property">performance</span>.<span class="hljs-title function_">eventLoopUtilization</span>()); 1348 }, <span class="hljs-number">100</span>).<span class="hljs-title function_">unref</span>(); 1349 <span class="hljs-keyword">return</span>; 1350} 1351 1352parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'msg'</span>)).<span class="hljs-title function_">unref</span>(); 1353(<span class="hljs-keyword">function</span> <span class="hljs-title function_">r</span>(<span class="hljs-params">n</span>) { 1354 <span class="hljs-keyword">if</span> (--n < <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span>; 1355 <span class="hljs-keyword">const</span> t = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(); 1356 <span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - t < <span class="hljs-number">300</span>); 1357 <span class="hljs-title function_">setImmediate</span>(r, n); 1358})(<span class="hljs-number">10</span>);</code> <button class="copy-button">copy</button></pre> 1359<p>The event loop utilization of a worker is available only after the <a href="#event-online"><code>'online'</code> 1360event</a> emitted, and if called before this, or after the <a href="#event-exit"><code>'exit'</code> 1361event</a>, then all properties have the value of <code>0</code>.</p> 1362<h4><code>worker.postMessage(value[, transferList])</code><span><a class="mark" href="#workerpostmessagevalue-transferlist" id="workerpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_postmessage_value_transferlist"></a></h4> 1363<div class="api_metadata"> 1364<span>Added in: v10.5.0</span> 1365</div> 1366<ul> 1367<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> 1368<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> 1369</ul> 1370<p>Send a message to the worker that is received via 1371<a href="#event-message"><code>require('node:worker_threads').parentPort.on('message')</code></a>. 1372See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more details.</p> 1373<h4><code>worker.ref()</code><span><a class="mark" href="#workerref" id="workerref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ref"></a></h4> 1374<div class="api_metadata"> 1375<span>Added in: v10.5.0</span> 1376</div> 1377<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker does 1378<em>not</em> let the program exit if it's the only active handle left (the default 1379behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again has 1380no effect.</p> 1381<h4><code>worker.resourceLimits</code><span><a class="mark" href="#workerresourcelimits_1" id="workerresourcelimits_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits_1"></a></h4> 1382<div class="api_metadata"> 1383<span>Added in: v13.2.0, v12.16.0</span> 1384</div> 1385<ul> 1386<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 1387<ul> 1388<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1389<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1390<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1391<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1392</ul> 1393</li> 1394</ul> 1395<p>Provides the set of JS engine resource constraints for this Worker thread. 1396If the <code>resourceLimits</code> option was passed to the <a href="#class-worker"><code>Worker</code></a> constructor, 1397this matches its values.</p> 1398<p>If the worker has stopped, the return value is an empty object.</p> 1399<h4><code>worker.stderr</code><span><a class="mark" href="#workerstderr" id="workerstderr">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stderr"></a></h4> 1400<div class="api_metadata"> 1401<span>Added in: v10.5.0</span> 1402</div> 1403<ul> 1404<li><a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 1405</ul> 1406<p>This is a readable stream which contains data written to <a href="process.html#processstderr"><code>process.stderr</code></a> 1407inside the worker thread. If <code>stderr: true</code> was not passed to the 1408<a href="#class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's 1409<a href="process.html#processstderr"><code>process.stderr</code></a> stream.</p> 1410<h4><code>worker.stdin</code><span><a class="mark" href="#workerstdin" id="workerstdin">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdin"></a></h4> 1411<div class="api_metadata"> 1412<span>Added in: v10.5.0</span> 1413</div> 1414<ul> 1415<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li> 1416</ul> 1417<p>If <code>stdin: true</code> was passed to the <a href="#class-worker"><code>Worker</code></a> constructor, this is a 1418writable stream. The data written to this stream will be made available in 1419the worker thread as <a href="process.html#processstdin"><code>process.stdin</code></a>.</p> 1420<h4><code>worker.stdout</code><span><a class="mark" href="#workerstdout" id="workerstdout">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdout"></a></h4> 1421<div class="api_metadata"> 1422<span>Added in: v10.5.0</span> 1423</div> 1424<ul> 1425<li><a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 1426</ul> 1427<p>This is a readable stream which contains data written to <a href="process.html#processstdout"><code>process.stdout</code></a> 1428inside the worker thread. If <code>stdout: true</code> was not passed to the 1429<a href="#class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's 1430<a href="process.html#processstdout"><code>process.stdout</code></a> stream.</p> 1431<h4><code>worker.terminate()</code><span><a class="mark" href="#workerterminate" id="workerterminate">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_terminate"></a></h4> 1432<div class="api_metadata"> 1433<details class="changelog"><summary>History</summary> 1434<table> 1435<tbody><tr><th>Version</th><th>Changes</th></tr> 1436<tr><td>v12.5.0</td> 1437<td><p>This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation.</p></td></tr> 1438<tr><td>v10.5.0</td> 1439<td><p><span>Added in: v10.5.0</span></p></td></tr> 1440</tbody></table> 1441</details> 1442</div> 1443<ul> 1444<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> 1445</ul> 1446<p>Stop all JavaScript execution in the worker thread as soon as possible. 1447Returns a Promise for the exit code that is fulfilled when the 1448<a href="#event-exit"><code>'exit'</code> event</a> is emitted.</p> 1449<h4><code>worker.threadId</code><span><a class="mark" href="#workerthreadid_1" id="workerthreadid_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid_1"></a></h4> 1450<div class="api_metadata"> 1451<span>Added in: v10.5.0</span> 1452</div> 1453<ul> 1454<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1455</ul> 1456<p>An integer identifier for the referenced thread. Inside the worker thread, 1457it is available as <a href="#workerthreadid"><code>require('node:worker_threads').threadId</code></a>. 1458This value is unique for each <code>Worker</code> instance inside a single process.</p> 1459<h4><code>worker.unref()</code><span><a class="mark" href="#workerunref" id="workerunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_unref"></a></h4> 1460<div class="api_metadata"> 1461<span>Added in: v10.5.0</span> 1462</div> 1463<p>Calling <code>unref()</code> on a worker allows the thread to exit if this is the only 1464active handle in the event system. If the worker is already <code>unref()</code>ed calling 1465<code>unref()</code> again has no effect.</p> 1466</section><section><h3>Notes<span><a class="mark" href="#notes" id="notes">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_notes"></a></h3> 1467<h4>Synchronous blocking of stdio<span><a class="mark" href="#synchronous-blocking-of-stdio" id="synchronous-blocking-of-stdio">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_synchronous_blocking_of_stdio"></a></h4> 1468<p><code>Worker</code>s utilize message passing via <a href="worker_threads.html#class-messageport" class="type"><MessagePort></a> to implement interactions 1469with <code>stdio</code>. This means that <code>stdio</code> output originating from a <code>Worker</code> can 1470get blocked by synchronous code on the receiving end that is blocking the 1471Node.js event loop.</p> 1472 1473<pre class="with-13-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> { 1474 <span class="hljs-title class_">Worker</span>, 1475 isMainThread, 1476} <span class="hljs-keyword">from</span> <span class="hljs-string">'worker_threads'</span>; 1477 1478<span class="hljs-keyword">if</span> (isMainThread) { 1479 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)); 1480 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">1e10</span>; n++) { 1481 <span class="hljs-comment">// Looping to simulate work.</span> 1482 } 1483} <span class="hljs-keyword">else</span> { 1484 <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span> 1485 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>); 1486}</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>; 1487 1488<span class="hljs-keyword">const</span> { 1489 <span class="hljs-title class_">Worker</span>, 1490 isMainThread, 1491} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>); 1492 1493<span class="hljs-keyword">if</span> (isMainThread) { 1494 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename); 1495 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">1e10</span>; n++) { 1496 <span class="hljs-comment">// Looping to simulate work.</span> 1497 } 1498} <span class="hljs-keyword">else</span> { 1499 <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span> 1500 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>); 1501}</code><button class="copy-button">copy</button></pre> 1502<h4>Launching worker threads from preload scripts<span><a class="mark" href="#launching-worker-threads-from-preload-scripts" id="launching-worker-threads-from-preload-scripts">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_launching_worker_threads_from_preload_scripts"></a></h4> 1503<p>Take care when launching worker threads from preload scripts (scripts loaded 1504and run using the <code>-r</code> command line flag). Unless the <code>execArgv</code> option is 1505explicitly set, new Worker threads automatically inherit the command line flags 1506from the running process and will preload the same preload scripts as the main 1507thread. If the preload script unconditionally launches a worker thread, every 1508thread spawned will spawn another until the application crashes.</p></section> 1509 <!-- API END --> 1510 </div> 1511 </div> 1512 </div> 1513</body> 1514</html> 1515