%PDF- %PDF-
Direktori : /usr/share/doc/nodejs/api/ |
Current File : //usr/share/doc/nodejs/api/events.html |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="nodejs.org:node-version" content="v18.19.1"> <title>Events | Node.js v18.19.1 Documentation</title> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <script async defer src="assets/api.js" type="text/javascript"></script> __JS_FLAVORED_DYNAMIC_CSS__ </head> <body class="alt apidoc" id="api-section-events"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="index.html" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> </ul> <hr class="line"/> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events active">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="permissions.html" class="nav-permissions">Permissions</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="test.html" class="nav-test">Test runner</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"/> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> <div id="column1" data-id="events" class="interior"> <header class="header"> <div class="header-container"> <h1>Node.js v18.19.1 documentation</h1> <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> <path fill="none" d="M0 0h24v24H0z" /> <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"/> <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"/> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> <path d="M0 0h24v24H0z" fill="none" /> <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"/> </svg> </button> </div> <div id="gtoc"> <ul> <li class="pinned-header">Node.js v18.19.1</li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Table of contents </a> <div class="picker"><div class="toc"><ul> <li><a href="#events">Events</a><ul> <li><a href="#passing-arguments-and-this-to-listeners">Passing arguments and <code>this</code> to listeners</a></li> <li><a href="#asynchronous-vs-synchronous">Asynchronous vs. synchronous</a></li> <li><a href="#handling-events-only-once">Handling events only once</a></li> <li><a href="#error-events">Error events</a></li> <li><a href="#capture-rejections-of-promises">Capture rejections of promises</a></li> <li><a href="#class-eventemitter">Class: <code>EventEmitter</code></a><ul> <li><a href="#event-newlistener">Event: <code>'newListener'</code></a></li> <li><a href="#event-removelistener">Event: <code>'removeListener'</code></a></li> <li><a href="#emitteraddlistenereventname-listener"><code>emitter.addListener(eventName, listener)</code></a></li> <li><a href="#emitteremiteventname-args"><code>emitter.emit(eventName[, ...args])</code></a></li> <li><a href="#emittereventnames"><code>emitter.eventNames()</code></a></li> <li><a href="#emittergetmaxlisteners"><code>emitter.getMaxListeners()</code></a></li> <li><a href="#emitterlistenercounteventname-listener"><code>emitter.listenerCount(eventName[, listener])</code></a></li> <li><a href="#emitterlistenerseventname"><code>emitter.listeners(eventName)</code></a></li> <li><a href="#emitteroffeventname-listener"><code>emitter.off(eventName, listener)</code></a></li> <li><a href="#emitteroneventname-listener"><code>emitter.on(eventName, listener)</code></a></li> <li><a href="#emitteronceeventname-listener"><code>emitter.once(eventName, listener)</code></a></li> <li><a href="#emitterprependlistenereventname-listener"><code>emitter.prependListener(eventName, listener)</code></a></li> <li><a href="#emitterprependoncelistenereventname-listener"><code>emitter.prependOnceListener(eventName, listener)</code></a></li> <li><a href="#emitterremovealllistenerseventname"><code>emitter.removeAllListeners([eventName])</code></a></li> <li><a href="#emitterremovelistenereventname-listener"><code>emitter.removeListener(eventName, listener)</code></a></li> <li><a href="#emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a></li> <li><a href="#emitterrawlistenerseventname"><code>emitter.rawListeners(eventName)</code></a></li> <li><a href="#emittersymbolfornodejsrejectionerr-eventname-args"><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code></a></li> </ul> </li> <li><a href="#eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a></li> <li><a href="#eventserrormonitor"><code>events.errorMonitor</code></a></li> <li><a href="#eventsgeteventlistenersemitterortarget-eventname"><code>events.getEventListeners(emitterOrTarget, eventName)</code></a></li> <li><a href="#eventsgetmaxlistenersemitterortarget"><code>events.getMaxListeners(emitterOrTarget)</code></a></li> <li><a href="#eventsonceemitter-name-options"><code>events.once(emitter, name[, options])</code></a><ul> <li><a href="#awaiting-multiple-events-emitted-on-processnexttick">Awaiting multiple events emitted on <code>process.nextTick()</code></a></li> </ul> </li> <li><a href="#eventscapturerejections"><code>events.captureRejections</code></a></li> <li><a href="#eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a></li> <li><a href="#eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a></li> <li><a href="#eventsonemitter-eventname-options"><code>events.on(emitter, eventName[, options])</code></a></li> <li><a href="#eventssetmaxlistenersn-eventtargets"><code>events.setMaxListeners(n[, ...eventTargets])</code></a></li> <li><a href="#eventsaddabortlistenersignal-resource"><code>events.addAbortListener(signal, resource)</code></a></li> <li><a href="#class-eventseventemitterasyncresource-extends-eventemitter">Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code></a><ul> <li><a href="#new-eventseventemitterasyncresourceoptions"><code>new events.EventEmitterAsyncResource([options])</code></a></li> <li><a href="#eventemitterasyncresourceasyncid"><code>eventemitterasyncresource.asyncId</code></a></li> <li><a href="#eventemitterasyncresourceasyncresource"><code>eventemitterasyncresource.asyncResource</code></a></li> <li><a href="#eventemitterasyncresourceemitdestroy"><code>eventemitterasyncresource.emitDestroy()</code></a></li> <li><a href="#eventemitterasyncresourcetriggerasyncid"><code>eventemitterasyncresource.triggerAsyncId</code></a></li> </ul> </li> <li><a href="#eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a><ul> <li><a href="#nodejs-eventtarget-vs-dom-eventtarget">Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code></a></li> <li><a href="#nodeeventtarget-vs-eventemitter"><code>NodeEventTarget</code> vs. <code>EventEmitter</code></a></li> <li><a href="#event-listener">Event listener</a></li> <li><a href="#eventtarget-error-handling"><code>EventTarget</code> error handling</a></li> <li><a href="#class-event">Class: <code>Event</code></a><ul> <li><a href="#eventbubbles"><code>event.bubbles</code></a></li> <li><a href="#eventcancelbubble"><code>event.cancelBubble</code></a></li> <li><a href="#eventcancelable"><code>event.cancelable</code></a></li> <li><a href="#eventcomposed"><code>event.composed</code></a></li> <li><a href="#eventcomposedpath"><code>event.composedPath()</code></a></li> <li><a href="#eventcurrenttarget"><code>event.currentTarget</code></a></li> <li><a href="#eventdefaultprevented"><code>event.defaultPrevented</code></a></li> <li><a href="#eventeventphase"><code>event.eventPhase</code></a></li> <li><a href="#eventistrusted"><code>event.isTrusted</code></a></li> <li><a href="#eventpreventdefault"><code>event.preventDefault()</code></a></li> <li><a href="#eventreturnvalue"><code>event.returnValue</code></a></li> <li><a href="#eventsrcelement"><code>event.srcElement</code></a></li> <li><a href="#eventstopimmediatepropagation"><code>event.stopImmediatePropagation()</code></a></li> <li><a href="#eventstoppropagation"><code>event.stopPropagation()</code></a></li> <li><a href="#eventtarget"><code>event.target</code></a></li> <li><a href="#eventtimestamp"><code>event.timeStamp</code></a></li> <li><a href="#eventtype"><code>event.type</code></a></li> </ul> </li> <li><a href="#class-eventtarget">Class: <code>EventTarget</code></a><ul> <li><a href="#eventtargetaddeventlistenertype-listener-options"><code>eventTarget.addEventListener(type, listener[, options])</code></a></li> <li><a href="#eventtargetdispatcheventevent"><code>eventTarget.dispatchEvent(event)</code></a></li> <li><a href="#eventtargetremoveeventlistenertype-listener-options"><code>eventTarget.removeEventListener(type, listener[, options])</code></a></li> </ul> </li> <li><a href="#class-customevent">Class: <code>CustomEvent</code></a><ul> <li><a href="#eventdetail"><code>event.detail</code></a></li> </ul> </li> <li><a href="#class-nodeeventtarget">Class: <code>NodeEventTarget</code></a><ul> <li><a href="#nodeeventtargetaddlistenertype-listener"><code>nodeEventTarget.addListener(type, listener)</code></a></li> <li><a href="#nodeeventtargetemittype-arg"><code>nodeEventTarget.emit(type, arg)</code></a></li> <li><a href="#nodeeventtargeteventnames"><code>nodeEventTarget.eventNames()</code></a></li> <li><a href="#nodeeventtargetlistenercounttype"><code>nodeEventTarget.listenerCount(type)</code></a></li> <li><a href="#nodeeventtargetsetmaxlistenersn"><code>nodeEventTarget.setMaxListeners(n)</code></a></li> <li><a href="#nodeeventtargetgetmaxlisteners"><code>nodeEventTarget.getMaxListeners()</code></a></li> <li><a href="#nodeeventtargetofftype-listener-options"><code>nodeEventTarget.off(type, listener[, options])</code></a></li> <li><a href="#nodeeventtargetontype-listener"><code>nodeEventTarget.on(type, listener)</code></a></li> <li><a href="#nodeeventtargetoncetype-listener"><code>nodeEventTarget.once(type, listener)</code></a></li> <li><a href="#nodeeventtargetremovealllistenerstype"><code>nodeEventTarget.removeAllListeners([type])</code></a></li> <li><a href="#nodeeventtargetremovelistenertype-listener-options"><code>nodeEventTarget.removeListener(type, listener[, options])</code></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </div></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Index </a> <div class="picker"><ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> <li> <a href="index.html">Index</a> </li> </ul> <hr class="line"/> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events active">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="permissions.html" class="nav-permissions">Permissions</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="test.html" class="nav-test">Test runner</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"/> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Other versions </a> <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v18.x/api/events.html">18.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v17.x/api/events.html">17.x</a></li> <li><a href="https://nodejs.org/docs/latest-v16.x/api/events.html">16.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v15.x/api/events.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/events.html">14.x</a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/events.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/events.html">12.x</a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/events.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/events.html">10.x</a></li> <li><a href="https://nodejs.org/docs/latest-v9.x/api/events.html">9.x</a></li> <li><a href="https://nodejs.org/docs/latest-v8.x/api/events.html">8.x</a></li> <li><a href="https://nodejs.org/docs/latest-v7.x/api/events.html">7.x</a></li> <li><a href="https://nodejs.org/docs/latest-v6.x/api/events.html">6.x</a></li> <li><a href="https://nodejs.org/docs/latest-v5.x/api/events.html">5.x</a></li> <li><a href="https://nodejs.org/docs/latest-v4.x/api/events.html">4.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.12.x/api/events.html">0.12.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.10.x/api/events.html">0.10.x</a></li></ol></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Options </a> <div class="picker"> <ul> <li> <a href="all.html">View on single page</a> </li> <li> <a href="events.json">View as JSON</a> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/events.md">Edit on GitHub</a></li> </ul> </div> </li> </ul> </div> <hr> </header> <details id="toc" open><summary>Table of contents</summary><ul> <li><a href="#events">Events</a><ul> <li><a href="#passing-arguments-and-this-to-listeners">Passing arguments and <code>this</code> to listeners</a></li> <li><a href="#asynchronous-vs-synchronous">Asynchronous vs. synchronous</a></li> <li><a href="#handling-events-only-once">Handling events only once</a></li> <li><a href="#error-events">Error events</a></li> <li><a href="#capture-rejections-of-promises">Capture rejections of promises</a></li> <li><a href="#class-eventemitter">Class: <code>EventEmitter</code></a><ul> <li><a href="#event-newlistener">Event: <code>'newListener'</code></a></li> <li><a href="#event-removelistener">Event: <code>'removeListener'</code></a></li> <li><a href="#emitteraddlistenereventname-listener"><code>emitter.addListener(eventName, listener)</code></a></li> <li><a href="#emitteremiteventname-args"><code>emitter.emit(eventName[, ...args])</code></a></li> <li><a href="#emittereventnames"><code>emitter.eventNames()</code></a></li> <li><a href="#emittergetmaxlisteners"><code>emitter.getMaxListeners()</code></a></li> <li><a href="#emitterlistenercounteventname-listener"><code>emitter.listenerCount(eventName[, listener])</code></a></li> <li><a href="#emitterlistenerseventname"><code>emitter.listeners(eventName)</code></a></li> <li><a href="#emitteroffeventname-listener"><code>emitter.off(eventName, listener)</code></a></li> <li><a href="#emitteroneventname-listener"><code>emitter.on(eventName, listener)</code></a></li> <li><a href="#emitteronceeventname-listener"><code>emitter.once(eventName, listener)</code></a></li> <li><a href="#emitterprependlistenereventname-listener"><code>emitter.prependListener(eventName, listener)</code></a></li> <li><a href="#emitterprependoncelistenereventname-listener"><code>emitter.prependOnceListener(eventName, listener)</code></a></li> <li><a href="#emitterremovealllistenerseventname"><code>emitter.removeAllListeners([eventName])</code></a></li> <li><a href="#emitterremovelistenereventname-listener"><code>emitter.removeListener(eventName, listener)</code></a></li> <li><a href="#emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a></li> <li><a href="#emitterrawlistenerseventname"><code>emitter.rawListeners(eventName)</code></a></li> <li><a href="#emittersymbolfornodejsrejectionerr-eventname-args"><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code></a></li> </ul> </li> <li><a href="#eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a></li> <li><a href="#eventserrormonitor"><code>events.errorMonitor</code></a></li> <li><a href="#eventsgeteventlistenersemitterortarget-eventname"><code>events.getEventListeners(emitterOrTarget, eventName)</code></a></li> <li><a href="#eventsgetmaxlistenersemitterortarget"><code>events.getMaxListeners(emitterOrTarget)</code></a></li> <li><a href="#eventsonceemitter-name-options"><code>events.once(emitter, name[, options])</code></a><ul> <li><a href="#awaiting-multiple-events-emitted-on-processnexttick">Awaiting multiple events emitted on <code>process.nextTick()</code></a></li> </ul> </li> <li><a href="#eventscapturerejections"><code>events.captureRejections</code></a></li> <li><a href="#eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a></li> <li><a href="#eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a></li> <li><a href="#eventsonemitter-eventname-options"><code>events.on(emitter, eventName[, options])</code></a></li> <li><a href="#eventssetmaxlistenersn-eventtargets"><code>events.setMaxListeners(n[, ...eventTargets])</code></a></li> <li><a href="#eventsaddabortlistenersignal-resource"><code>events.addAbortListener(signal, resource)</code></a></li> <li><a href="#class-eventseventemitterasyncresource-extends-eventemitter">Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code></a><ul> <li><a href="#new-eventseventemitterasyncresourceoptions"><code>new events.EventEmitterAsyncResource([options])</code></a></li> <li><a href="#eventemitterasyncresourceasyncid"><code>eventemitterasyncresource.asyncId</code></a></li> <li><a href="#eventemitterasyncresourceasyncresource"><code>eventemitterasyncresource.asyncResource</code></a></li> <li><a href="#eventemitterasyncresourceemitdestroy"><code>eventemitterasyncresource.emitDestroy()</code></a></li> <li><a href="#eventemitterasyncresourcetriggerasyncid"><code>eventemitterasyncresource.triggerAsyncId</code></a></li> </ul> </li> <li><a href="#eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a><ul> <li><a href="#nodejs-eventtarget-vs-dom-eventtarget">Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code></a></li> <li><a href="#nodeeventtarget-vs-eventemitter"><code>NodeEventTarget</code> vs. <code>EventEmitter</code></a></li> <li><a href="#event-listener">Event listener</a></li> <li><a href="#eventtarget-error-handling"><code>EventTarget</code> error handling</a></li> <li><a href="#class-event">Class: <code>Event</code></a><ul> <li><a href="#eventbubbles"><code>event.bubbles</code></a></li> <li><a href="#eventcancelbubble"><code>event.cancelBubble</code></a></li> <li><a href="#eventcancelable"><code>event.cancelable</code></a></li> <li><a href="#eventcomposed"><code>event.composed</code></a></li> <li><a href="#eventcomposedpath"><code>event.composedPath()</code></a></li> <li><a href="#eventcurrenttarget"><code>event.currentTarget</code></a></li> <li><a href="#eventdefaultprevented"><code>event.defaultPrevented</code></a></li> <li><a href="#eventeventphase"><code>event.eventPhase</code></a></li> <li><a href="#eventistrusted"><code>event.isTrusted</code></a></li> <li><a href="#eventpreventdefault"><code>event.preventDefault()</code></a></li> <li><a href="#eventreturnvalue"><code>event.returnValue</code></a></li> <li><a href="#eventsrcelement"><code>event.srcElement</code></a></li> <li><a href="#eventstopimmediatepropagation"><code>event.stopImmediatePropagation()</code></a></li> <li><a href="#eventstoppropagation"><code>event.stopPropagation()</code></a></li> <li><a href="#eventtarget"><code>event.target</code></a></li> <li><a href="#eventtimestamp"><code>event.timeStamp</code></a></li> <li><a href="#eventtype"><code>event.type</code></a></li> </ul> </li> <li><a href="#class-eventtarget">Class: <code>EventTarget</code></a><ul> <li><a href="#eventtargetaddeventlistenertype-listener-options"><code>eventTarget.addEventListener(type, listener[, options])</code></a></li> <li><a href="#eventtargetdispatcheventevent"><code>eventTarget.dispatchEvent(event)</code></a></li> <li><a href="#eventtargetremoveeventlistenertype-listener-options"><code>eventTarget.removeEventListener(type, listener[, options])</code></a></li> </ul> </li> <li><a href="#class-customevent">Class: <code>CustomEvent</code></a><ul> <li><a href="#eventdetail"><code>event.detail</code></a></li> </ul> </li> <li><a href="#class-nodeeventtarget">Class: <code>NodeEventTarget</code></a><ul> <li><a href="#nodeeventtargetaddlistenertype-listener"><code>nodeEventTarget.addListener(type, listener)</code></a></li> <li><a href="#nodeeventtargetemittype-arg"><code>nodeEventTarget.emit(type, arg)</code></a></li> <li><a href="#nodeeventtargeteventnames"><code>nodeEventTarget.eventNames()</code></a></li> <li><a href="#nodeeventtargetlistenercounttype"><code>nodeEventTarget.listenerCount(type)</code></a></li> <li><a href="#nodeeventtargetsetmaxlistenersn"><code>nodeEventTarget.setMaxListeners(n)</code></a></li> <li><a href="#nodeeventtargetgetmaxlisteners"><code>nodeEventTarget.getMaxListeners()</code></a></li> <li><a href="#nodeeventtargetofftype-listener-options"><code>nodeEventTarget.off(type, listener[, options])</code></a></li> <li><a href="#nodeeventtargetontype-listener"><code>nodeEventTarget.on(type, listener)</code></a></li> <li><a href="#nodeeventtargetoncetype-listener"><code>nodeEventTarget.once(type, listener)</code></a></li> <li><a href="#nodeeventtargetremovealllistenerstype"><code>nodeEventTarget.removeAllListeners([type])</code></a></li> <li><a href="#nodeeventtargetremovelistenertype-listener-options"><code>nodeEventTarget.removeListener(type, listener[, options])</code></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </details> <div id="apicontent"> <h2>Events<span><a class="mark" href="#events" id="events">#</a></span><a aria-hidden="true" class="legacy" id="events_events"></a></h2> <!--introduced_in=v0.10.0--> <blockquote> <p>Stability: 2 - Stable</p> </blockquote> <!--type=module--> <!-- source_link=lib/events.js --> <p>Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause <code>Function</code> objects ("listeners") to be called.</p> <p>For instance: a <a href="net.html#class-netserver"><code>net.Server</code></a> object emits an event each time a peer connects to it; a <a href="fs.html#class-fsreadstream"><code>fs.ReadStream</code></a> emits an event when the file is opened; a <a href="stream.html">stream</a> emits an event whenever data is available to be read.</p> <p>All objects that emit events are instances of the <code>EventEmitter</code> class. These objects expose an <code>eventEmitter.on()</code> function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.</p> <p>When the <code>EventEmitter</code> object emits an event, all of the functions attached to that specific event are called <em>synchronously</em>. Any values returned by the called listeners are <em>ignored</em> and discarded.</p> <p>The following example shows a simple <code>EventEmitter</code> instance with a single listener. The <code>eventEmitter.on()</code> method is used to register listeners, while the <code>eventEmitter.emit()</code> method is used to trigger the event.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event'); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event'); </code></pre> <section><h3>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#passing-arguments-and-this-to-listeners" id="passing-arguments-and-this-to-listeners">#</a></span><a aria-hidden="true" class="legacy" id="events_passing_arguments_and_this_to_listeners"></a></h3> <p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be passed to the listener functions. Keep in mind that when an ordinary listener function is called, the standard <code>this</code> keyword is intentionally set to reference the <code>EventEmitter</code> instance to which the listener is attached.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // Prints: // a b MyEmitter { // _events: [Object: null prototype] { event: [Function (anonymous)] }, // _eventsCount: 1, // _maxListeners: undefined, // [Symbol(kCapture)]: false // } true }); myEmitter.emit('event', 'a', 'b'); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // Prints: // a b MyEmitter { // _events: [Object: null prototype] { event: [Function (anonymous)] }, // _eventsCount: 1, // _maxListeners: undefined, // [Symbol(kCapture)]: false // } true }); myEmitter.emit('event', 'a', 'b'); </code></pre> <p>It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the <code>this</code> keyword will no longer reference the <code>EventEmitter</code> instance:</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b {} }); myEmitter.emit('event', 'a', 'b'); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b {} }); myEmitter.emit('event', 'a', 'b'); </code></pre> </section><section><h3>Asynchronous vs. synchronous<span><a class="mark" href="#asynchronous-vs-synchronous" id="asynchronous-vs-synchronous">#</a></span><a aria-hidden="true" class="legacy" id="events_asynchronous_vs_synchronous"></a></h3> <p>The <code>EventEmitter</code> calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the <code>setImmediate()</code> or <code>process.nextTick()</code> methods:</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); }); myEmitter.emit('event', 'a', 'b'); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); }); myEmitter.emit('event', 'a', 'b'); </code></pre> </section><section><h3>Handling events only once<span><a class="mark" href="#handling-events-only-once" id="handling-events-only-once">#</a></span><a aria-hidden="true" class="legacy" id="events_handling_events_only_once"></a></h3> <p>When a listener is registered using the <code>eventEmitter.on()</code> method, that listener is invoked <em>every time</em> the named event is emitted.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.on('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Prints: 2 </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.on('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Prints: 2 </code></pre> <p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener that is called at most once for a particular event. Once the event is emitted, the listener is unregistered and <em>then</em> called.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.once('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Ignored </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.once('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Ignored </code></pre> </section><section><h3>Error events<span><a class="mark" href="#error-events" id="error-events">#</a></span><a aria-hidden="true" class="legacy" id="events_error_events"></a></h3> <p>When an error occurs within an <code>EventEmitter</code> instance, the typical action is for an <code>'error'</code> event to be emitted. These are treated as special cases within Node.js.</p> <p>If an <code>EventEmitter</code> does <em>not</em> have at least one listener registered for the <code>'error'</code> event, and an <code>'error'</code> event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.js </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.js </code></pre> <p>To guard against crashing the Node.js process the <a href="domain.html"><code>domain</code></a> module can be used. (Note, however, that the <code>node:domain</code> module is deprecated.)</p> <p>As a best practice, listeners should always be added for the <code>'error'</code> events.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('error', (err) => { console.error('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an error </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('error', (err) => { console.error('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an error </code></pre> <p>It is possible to monitor <code>'error'</code> events without consuming the emitted error by installing a listener using the symbol <code>events.errorMonitor</code>.</p> <pre><code class="language-mjs">import { EventEmitter, errorMonitor } from 'node:events'; const myEmitter = new EventEmitter(); myEmitter.on(errorMonitor, (err) => { MyMonitoringTool.log(err); }); myEmitter.emit('error', new Error('whoops!')); // Still throws and crashes Node.js </code></pre> <pre><code class="language-cjs">const { EventEmitter, errorMonitor } = require('node:events'); const myEmitter = new EventEmitter(); myEmitter.on(errorMonitor, (err) => { MyMonitoringTool.log(err); }); myEmitter.emit('error', new Error('whoops!')); // Still throws and crashes Node.js </code></pre> </section><section><h3>Capture rejections of promises<span><a class="mark" href="#capture-rejections-of-promises" id="capture-rejections-of-promises">#</a></span><a aria-hidden="true" class="legacy" id="events_capture_rejections_of_promises"></a></h3> <p>Using <code>async</code> functions with event handlers is problematic, because it can lead to an unhandled rejection in case of a thrown exception:</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); ee.on('something', async (value) => { throw new Error('kaboom'); }); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const ee = new EventEmitter(); ee.on('something', async (value) => { throw new Error('kaboom'); }); </code></pre> <p>The <code>captureRejections</code> option in the <code>EventEmitter</code> constructor or the global setting change this behavior, installing a <code>.then(undefined, handler)</code> handler on the <code>Promise</code>. This handler routes the exception asynchronously to the <a href="#emittersymbolfornodejsrejectionerr-eventname-args"><code>Symbol.for('nodejs.rejection')</code></a> method if there is one, or to <a href="#error-events"><code>'error'</code></a> event handler if there is none.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const ee1 = new EventEmitter({ captureRejections: true }); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log); const ee2 = new EventEmitter({ captureRejections: true }); ee2.on('something', async (value) => { throw new Error('kaboom'); }); ee2[Symbol.for('nodejs.rejection')] = console.log; </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const ee1 = new EventEmitter({ captureRejections: true }); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log); const ee2 = new EventEmitter({ captureRejections: true }); ee2.on('something', async (value) => { throw new Error('kaboom'); }); ee2[Symbol.for('nodejs.rejection')] = console.log; </code></pre> <p>Setting <code>events.captureRejections = true</code> will change the default for all new instances of <code>EventEmitter</code>.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; EventEmitter.captureRejections = true; const ee1 = new EventEmitter(); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log); </code></pre> <pre><code class="language-cjs">const events = require('node:events'); events.captureRejections = true; const ee1 = new events.EventEmitter(); ee1.on('something', async (value) => { throw new Error('kaboom'); }); ee1.on('error', console.log); </code></pre> <p>The <code>'error'</code> events that are generated by the <code>captureRejections</code> behavior do not have a catch handler to avoid infinite error loops: the recommendation is to <strong>not use <code>async</code> functions as <code>'error'</code> event handlers</strong>.</p> </section><section><h3>Class: <code>EventEmitter</code><span><a class="mark" href="#class-eventemitter" id="class-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_class_eventemitter"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v13.4.0, v12.16.0</td> <td><p>Added captureRejections option.</p> </td></tr> <tr><td>v0.1.26</td> <td><p><span>Added in: v0.1.26</span></p> </td></tr> </table> </details> </div><p>The <code>EventEmitter</code> class is defined and exposed by the <code>node:events</code> module:</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); </code></pre> <p>All <code>EventEmitter</code>s emit the event <code>'newListener'</code> when new listeners are added and <code>'removeListener'</code> when existing listeners are removed.</p> <p>It supports the following option:</p> <ul> <li><code>captureRejections</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> It enables <a href="#capture-rejections-of-promises">automatic capturing of promise rejection</a>. <strong>Default:</strong> <code>false</code>.</li> </ul> <h4>Event: <code>'newListener'</code><span><a class="mark" href="#event-newlistener" id="event-newlistener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_newlistener"></a></h4> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div><ul> <li><code>eventName</code> {string|symbol} The name of the event being listened for</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li> </ul> <p>The <code>EventEmitter</code> instance will emit its own <code>'newListener'</code> event <em>before</em> a listener is added to its internal array of listeners.</p> <p>Listeners registered for the <code>'newListener'</code> event are passed the event name and a reference to the listener being added.</p> <p>The fact that the event is triggered before adding the listener has a subtle but important side effect: any <em>additional</em> listeners registered to the same <code>name</code> <em>within</em> the <code>'newListener'</code> callback are inserted <em>before</em> the listener that is in the process of being added.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); // Only do this once so we don't loop forever myEmitter.once('newListener', (event, listener) => { if (event === 'event') { // Insert a new listener in front myEmitter.on('event', () => { console.log('B'); }); } }); myEmitter.on('event', () => { console.log('A'); }); myEmitter.emit('event'); // Prints: // B // A </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); // Only do this once so we don't loop forever myEmitter.once('newListener', (event, listener) => { if (event === 'event') { // Insert a new listener in front myEmitter.on('event', () => { console.log('B'); }); } }); myEmitter.on('event', () => { console.log('A'); }); myEmitter.emit('event'); // Prints: // B // A </code></pre> <h4>Event: <code>'removeListener'</code><span><a class="mark" href="#event-removelistener" id="event-removelistener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_removelistener"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.1.0, v4.7.0</td> <td><p>For listeners attached using <code>.once()</code>, the <code>listener</code> argument now yields the original listener function.</p> </td></tr> <tr><td>v0.9.3</td> <td><p><span>Added in: v0.9.3</span></p> </td></tr> </table> </details> </div><ul> <li><code>eventName</code> {string|symbol} The event name</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li> </ul> <p>The <code>'removeListener'</code> event is emitted <em>after</em> the <code>listener</code> is removed.</p> <h4><code>emitter.addListener(eventName, listener)</code><span><a class="mark" href="#emitteraddlistenereventname-listener" id="emitteraddlistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_addlistener_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Alias for <code>emitter.on(eventName, listener)</code>.</p> <h4><code>emitter.emit(eventName[, ...args])</code><span><a class="mark" href="#emitteremiteventname-args" id="emitteremiteventname-args">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_emit_eventname_args"></a></h4> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Synchronously calls each of the listeners registered for the event named <code>eventName</code>, in the order they were registered, passing the supplied arguments to each.</p> <p>Returns <code>true</code> if the event had listeners, <code>false</code> otherwise.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener </code></pre> <h4><code>emitter.eventNames()</code><span><a class="mark" href="#emittereventnames" id="emittereventnames">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_eventnames"></a></h4> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div><ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li> </ul> <p>Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or <code>Symbol</code>s.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] </code></pre> <h4><code>emitter.getMaxListeners()</code><span><a class="mark" href="#emittergetmaxlisteners" id="emittergetmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_getmaxlisteners"></a></h4> <div class="api_metadata"> <span>Added in: v1.0.0</span> </div><ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns the current max listener value for the <code>EventEmitter</code> which is either set by <a href="#emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> or defaults to <a href="#eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a>.</p> <h4><code>emitter.listenerCount(eventName[, listener])</code><span><a class="mark" href="#emitterlistenercounteventname-listener" id="emitterlistenercounteventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listenercount_eventname_listener"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.16.0</td> <td><p>Added the <code>listener</code> argument.</p> </td></tr> <tr><td>v3.2.0</td> <td><p><span>Added in: v3.2.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>eventName</code> {string|symbol} The name of the event being listened for</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns the number of listeners listening for the event named <code>eventName</code>. If <code>listener</code> is provided, it will return how many times the listener is found in the list of the listeners of the event.</p> <h4><code>emitter.listeners(eventName)</code><span><a class="mark" href="#emitterlistenerseventname" id="emitterlistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listeners_eventname"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>For listeners attached using <code>.once()</code> this returns the original listeners instead of wrapper functions now.</p> </td></tr> <tr><td>v0.1.26</td> <td><p><span>Added in: v0.1.26</span></p> </td></tr> </table> </details> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li> </ul> <p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p> <pre><code class="language-js">server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] </code></pre> <h4><code>emitter.off(eventName, listener)</code><span><a class="mark" href="#emitteroffeventname-listener" id="emitteroffeventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_off_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Alias for <a href="#emitterremovelistenereventname-listener"><code>emitter.removeListener()</code></a>.</p> <h4><code>emitter.on(eventName, listener)</code><span><a class="mark" href="#emitteroneventname-listener" id="emitteroneventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_on_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v0.1.101</span> </div><ul> <li><code>eventName</code> {string|symbol} The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds the <code>listener</code> function to the end of the listeners array for the event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has already been added. Multiple calls passing the same combination of <code>eventName</code> and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple times.</p> <pre><code class="language-js">server.on('connection', (stream) => { console.log('someone connected!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <p>By default, event listeners are invoked in the order they are added. The <code>emitter.prependListener()</code> method can be used as an alternative to add the event listener to the beginning of the listeners array.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a </code></pre> <h4><code>emitter.once(eventName, listener)</code><span><a class="mark" href="#emitteronceeventname-listener" id="emitteronceeventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_once_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div><ul> <li><code>eventName</code> {string|symbol} The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code>. The next time <code>eventName</code> is triggered, this listener is removed and then invoked.</p> <pre><code class="language-js">server.once('connection', (stream) => { console.log('Ah, we have our first user!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <p>By default, event listeners are invoked in the order they are added. The <code>emitter.prependOnceListener()</code> method can be used as an alternative to add the event listener to the beginning of the listeners array.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a </code></pre> <h4><code>emitter.prependListener(eventName, listener)</code><span><a class="mark" href="#emitterprependlistenereventname-listener" id="emitterprependlistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_prependlistener_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div><ul> <li><code>eventName</code> {string|symbol} The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds the <code>listener</code> function to the <em>beginning</em> of the listeners array for the event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has already been added. Multiple calls passing the same combination of <code>eventName</code> and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple times.</p> <pre><code class="language-js">server.prependListener('connection', (stream) => { console.log('someone connected!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h4><code>emitter.prependOnceListener(eventName, listener)</code><span><a class="mark" href="#emitterprependoncelistenereventname-listener" id="emitterprependoncelistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_prependoncelistener_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div><ul> <li><code>eventName</code> {string|symbol} The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code> to the <em>beginning</em> of the listeners array. The next time <code>eventName</code> is triggered, this listener is removed, and then invoked.</p> <pre><code class="language-js">server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h4><code>emitter.removeAllListeners([eventName])</code><span><a class="mark" href="#emitterremovealllistenerseventname" id="emitterremovealllistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_removealllisteners_eventname"></a></h4> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Removes all listeners, or those of the specified <code>eventName</code>.</p> <p>It is bad practice to remove listeners added elsewhere in the code, particularly when the <code>EventEmitter</code> instance was created by some other component or module (e.g. sockets or file streams).</p> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h4><code>emitter.removeListener(eventName, listener)</code><span><a class="mark" href="#emitterremovelistenereventname-listener" id="emitterremovelistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_removelistener_eventname_listener"></a></h4> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Removes the specified <code>listener</code> from the listener array for the event named <code>eventName</code>.</p> <pre><code class="language-js">const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback); </code></pre> <p><code>removeListener()</code> will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified <code>eventName</code>, then <code>removeListener()</code> must be called multiple times to remove each instance.</p> <p>Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any <code>removeListener()</code> or <code>removeAllListeners()</code> calls <em>after</em> emitting and <em>before</em> the last listener finishes execution will not remove them from <code>emit()</code> in progress. Subsequent events behave as expected.</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A </code></pre> <p>Because listeners are managed using an internal array, calling this will change the position indices of any listener registered <em>after</em> the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the <code>emitter.listeners()</code> method will need to be recreated.</p> <p>When a single function has been added as a handler multiple times for a single event (as in the example below), <code>removeListener()</code> will remove the most recently added instance. In the example the <code>once('ping')</code> listener is removed:</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping'); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping'); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h4><code>emitter.setMaxListeners(n)</code><span><a class="mark" href="#emittersetmaxlistenersn" id="emittersetmaxlistenersn">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_setmaxlisteners_n"></a></h4> <div class="api_metadata"> <span>Added in: v0.3.5</span> </div><ul> <li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> </ul> <p>By default <code>EventEmitter</code>s will print a warning if more than <code>10</code> listeners are added for a particular event. This is a useful default that helps finding memory leaks. The <code>emitter.setMaxListeners()</code> method allows the limit to be modified for this specific <code>EventEmitter</code> instance. The value can be set to <code>Infinity</code> (or <code>0</code>) to indicate an unlimited number of listeners.</p> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h4><code>emitter.rawListeners(eventName)</code><span><a class="mark" href="#emitterrawlistenerseventname" id="emitterrawlistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_rawlisteners_eventname"></a></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div><ul> <li><code>eventName</code> {string|symbol}</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li> </ul> <p>Returns a copy of the array of listeners for the event named <code>eventName</code>, including any wrappers (such as those created by <code>.once()</code>).</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); </code></pre> <h4><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code><span><a class="mark" href="#emittersymbolfornodejsrejectionerr-eventname-args" id="emittersymbolfornodejsrejectionerr-eventname-args">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_symbol_for_nodejs_rejection_err_eventname_args"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.4.0, v16.14.0</td> <td><p>No longer experimental.</p> </td></tr> <tr><td>v13.4.0, v12.16.0</td> <td><p><span>Added in: v13.4.0, v12.16.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>err</code> Error</li> <li><code>eventName</code> {string|symbol}</li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>The <code>Symbol.for('nodejs.rejection')</code> method is called in case a promise rejection happens when emitting an event and <a href="#capture-rejections-of-promises"><code>captureRejections</code></a> is enabled on the emitter. It is possible to use <a href="#eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a> in place of <code>Symbol.for('nodejs.rejection')</code>.</p> <pre><code class="language-mjs">import { EventEmitter, captureRejectionSymbol } from 'node:events'; class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } } </code></pre> <pre><code class="language-cjs">const { EventEmitter, captureRejectionSymbol } = require('node:events'); class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } } </code></pre> </section><section><h3><code>events.defaultMaxListeners</code><span><a class="mark" href="#eventsdefaultmaxlisteners" id="eventsdefaultmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_events_defaultmaxlisteners"></a></h3> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div><p>By default, a maximum of <code>10</code> listeners can be registered for any single event. This limit can be changed for individual <code>EventEmitter</code> instances using the <a href="#emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> method. To change the default for <em>all</em> <code>EventEmitter</code> instances, the <code>events.defaultMaxListeners</code> property can be used. If this value is not a positive number, a <code>RangeError</code> is thrown.</p> <p>Take caution when setting the <code>events.defaultMaxListeners</code> because the change affects <em>all</em> <code>EventEmitter</code> instances, including those created before the change is made. However, calling <a href="#emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> still has precedence over <code>events.defaultMaxListeners</code>.</p> <p>This is not a hard limit. The <code>EventEmitter</code> instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any single <code>EventEmitter</code>, the <code>emitter.getMaxListeners()</code> and <code>emitter.setMaxListeners()</code> methods can be used to temporarily avoid this warning:</p> <pre><code class="language-mjs">import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); }); </code></pre> <pre><code class="language-cjs">const EventEmitter = require('node:events'); const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); }); </code></pre> <p>The <a href="cli.html#--trace-warnings"><code>--trace-warnings</code></a> command-line flag can be used to display the stack trace for such warnings.</p> <p>The emitted warning can be inspected with <a href="process.html#event-warning"><code>process.on('warning')</code></a> and will have the additional <code>emitter</code>, <code>type</code>, and <code>count</code> properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Its <code>name</code> property is set to <code>'MaxListenersExceededWarning'</code>.</p> </section><section><h3><code>events.errorMonitor</code><span><a class="mark" href="#eventserrormonitor" id="eventserrormonitor">#</a></span><a aria-hidden="true" class="legacy" id="events_events_errormonitor"></a></h3> <div class="api_metadata"> <span>Added in: v13.6.0, v12.17.0</span> </div><p>This symbol shall be used to install a listener for only monitoring <code>'error'</code> events. Listeners installed using this symbol are called before the regular <code>'error'</code> listeners are called.</p> <p>Installing a listener using this symbol does not change the behavior once an <code>'error'</code> event is emitted. Therefore, the process will still crash if no regular <code>'error'</code> listener is installed.</p> </section><section><h3><code>events.getEventListeners(emitterOrTarget, eventName)</code><span><a class="mark" href="#eventsgeteventlistenersemitterortarget-eventname" id="eventsgeteventlistenersemitterortarget-eventname">#</a></span><a aria-hidden="true" class="legacy" id="events_events_geteventlisteners_emitterortarget_eventname"></a></h3> <div class="api_metadata"> <span>Added in: v15.2.0, v14.17.0</span> </div><ul> <li><code>emitterOrTarget</code> {EventEmitter|EventTarget}</li> <li><code>eventName</code> {string|symbol}</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li> </ul> <p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p> <p>For <code>EventEmitter</code>s this behaves exactly the same as calling <code>.listeners</code> on the emitter.</p> <p>For <code>EventTarget</code>s this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.</p> <pre><code class="language-mjs">import { getEventListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] } </code></pre> <pre><code class="language-cjs">const { getEventListeners, EventEmitter } = require('node:events'); { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] } </code></pre> </section><section><h3><code>events.getMaxListeners(emitterOrTarget)</code><span><a class="mark" href="#eventsgetmaxlistenersemitterortarget" id="eventsgetmaxlistenersemitterortarget">#</a></span><a aria-hidden="true" class="legacy" id="events_events_getmaxlisteners_emitterortarget"></a></h3> <div class="api_metadata"> <span>Added in: v18.17.0</span> </div><ul> <li><code>emitterOrTarget</code> {EventEmitter|EventTarget}</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the currently set max amount of listeners.</p> <p>For <code>EventEmitter</code>s this behaves exactly the same as calling <code>.getMaxListeners</code> on the emitter.</p> <p>For <code>EventTarget</code>s this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.</p> <pre><code class="language-mjs">import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 } </code></pre> <pre><code class="language-cjs">const { getMaxListeners, setMaxListeners, EventEmitter } = require('node:events'); { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 } </code></pre> </section><section><h3><code>events.once(emitter, name[, options])</code><span><a class="mark" href="#eventsonceemitter-name-options" id="eventsonceemitter-name-options">#</a></span><a aria-hidden="true" class="legacy" id="events_events_once_emitter_name_options"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v15.0.0</td> <td><p>The <code>signal</code> option is supported now.</p> </td></tr> <tr><td>v11.13.0, v10.16.0</td> <td><p><span>Added in: v11.13.0, v10.16.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>emitter</code> <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Can be used to cancel waiting for the event.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Creates a <code>Promise</code> that is fulfilled when the <code>EventEmitter</code> emits the given event or that is rejected if the <code>EventEmitter</code> emits <code>'error'</code> while waiting. The <code>Promise</code> will resolve with an array of all the arguments emitted to the given event.</p> <p>This method is intentionally generic and works with the web platform <a href="https://dom.spec.whatwg.org/#interface-eventtarget">EventTarget</a> interface, which has no special <code>'error'</code> event semantics and does not listen to the <code>'error'</code> event.</p> <pre><code class="language-mjs">import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); } </code></pre> <pre><code class="language-cjs">const { once, EventEmitter } = require('node:events'); async function run() { const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); } } run(); </code></pre> <p>The special handling of the <code>'error'</code> event is only used when <code>events.once()</code> is used to wait for another event. If <code>events.once()</code> is used to wait for the '<code>error'</code> event itself, then it is treated as any other kind of event without special handling:</p> <pre><code class="language-mjs">import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom </code></pre> <pre><code class="language-cjs">const { EventEmitter, once } = require('node:events'); const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom </code></pre> <p>An <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> can be used to cancel waiting for the event:</p> <pre><code class="language-mjs">import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled! </code></pre> <pre><code class="language-cjs">const { EventEmitter, once } = require('node:events'); const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled! </code></pre> <h4>Awaiting multiple events emitted on <code>process.nextTick()</code><span><a class="mark" href="#awaiting-multiple-events-emitted-on-processnexttick" id="awaiting-multiple-events-emitted-on-processnexttick">#</a></span><a aria-hidden="true" class="legacy" id="events_awaiting_multiple_events_emitted_on_process_nexttick"></a></h4> <p>There is an edge case worth noting when using the <code>events.once()</code> function to await multiple events emitted on in the same batch of <code>process.nextTick()</code> operations, or whenever multiple events are emitted synchronously. Specifically, because the <code>process.nextTick()</code> queue is drained before the <code>Promise</code> microtask queue, and because <code>EventEmitter</code> emits all events synchronously, it is possible for <code>events.once()</code> to miss an event.</p> <pre><code class="language-mjs">import { EventEmitter, once } from 'node:events'; import process from 'node:process'; const myEE = new EventEmitter(); async function foo() { await once(myEE, 'bar'); console.log('bar'); // This Promise will never resolve because the 'foo' event will // have already been emitted before the Promise is created. await once(myEE, 'foo'); console.log('foo'); } process.nextTick(() => { myEE.emit('bar'); myEE.emit('foo'); }); foo().then(() => console.log('done')); </code></pre> <pre><code class="language-cjs">const { EventEmitter, once } = require('node:events'); const myEE = new EventEmitter(); async function foo() { await once(myEE, 'bar'); console.log('bar'); // This Promise will never resolve because the 'foo' event will // have already been emitted before the Promise is created. await once(myEE, 'foo'); console.log('foo'); } process.nextTick(() => { myEE.emit('bar'); myEE.emit('foo'); }); foo().then(() => console.log('done')); </code></pre> <p>To catch both events, create each of the Promises <em>before</em> awaiting either of them, then it becomes possible to use <code>Promise.all()</code>, <code>Promise.race()</code>, or <code>Promise.allSettled()</code>:</p> <pre><code class="language-mjs">import { EventEmitter, once } from 'node:events'; import process from 'node:process'; const myEE = new EventEmitter(); async function foo() { await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]); console.log('foo', 'bar'); } process.nextTick(() => { myEE.emit('bar'); myEE.emit('foo'); }); foo().then(() => console.log('done')); </code></pre> <pre><code class="language-cjs">const { EventEmitter, once } = require('node:events'); const myEE = new EventEmitter(); async function foo() { await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]); console.log('foo', 'bar'); } process.nextTick(() => { myEE.emit('bar'); myEE.emit('foo'); }); foo().then(() => console.log('done')); </code></pre> </section><section><h3><code>events.captureRejections</code><span><a class="mark" href="#eventscapturerejections" id="eventscapturerejections">#</a></span><a aria-hidden="true" class="legacy" id="events_events_capturerejections"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.4.0, v16.14.0</td> <td><p>No longer experimental.</p> </td></tr> <tr><td>v13.4.0, v12.16.0</td> <td><p><span>Added in: v13.4.0, v12.16.0</span></p> </td></tr> </table> </details> </div><p>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></p> <p>Change the default <code>captureRejections</code> option on all new <code>EventEmitter</code> objects.</p> </section><section><h3><code>events.captureRejectionSymbol</code><span><a class="mark" href="#eventscapturerejectionsymbol" id="eventscapturerejectionsymbol">#</a></span><a aria-hidden="true" class="legacy" id="events_events_capturerejectionsymbol"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.4.0, v16.14.0</td> <td><p>No longer experimental.</p> </td></tr> <tr><td>v13.4.0, v12.16.0</td> <td><p><span>Added in: v13.4.0, v12.16.0</span></p> </td></tr> </table> </details> </div><p>Value: <code>Symbol.for('nodejs.rejection')</code></p> <p>See how to write a custom <a href="#emittersymbolfornodejsrejectionerr-eventname-args">rejection handler</a>.</p> </section><section><h3><code>events.listenerCount(emitter, eventName)</code><span><a class="mark" href="#eventslistenercountemitter-eventname" id="eventslistenercountemitter-eventname">#</a></span><a aria-hidden="true" class="legacy" id="events_events_listenercount_emitter_eventname"></a></h3> <div class="api_metadata"> <span>Added in: v0.9.12</span><span>Deprecated since: v3.2.0</span> </div><blockquote> <p>Stability: 0 - Deprecated: Use <a href="#emitterlistenercounteventname-listener"><code>emitter.listenerCount()</code></a> instead.</p> </blockquote> <ul> <li><code>emitter</code> <a href="events.html#class-eventemitter" class="type"><EventEmitter></a> The emitter to query</li> <li><code>eventName</code> {string|symbol} The event name</li> </ul> <p>A class method that returns the number of listeners for the given <code>eventName</code> registered on the given <code>emitter</code>.</p> <pre><code class="language-mjs">import { EventEmitter, listenerCount } from 'node:events'; const myEmitter = new EventEmitter(); myEmitter.on('event', () => {}); myEmitter.on('event', () => {}); console.log(listenerCount(myEmitter, 'event')); // Prints: 2 </code></pre> <pre><code class="language-cjs">const { EventEmitter, listenerCount } = require('node:events'); const myEmitter = new EventEmitter(); myEmitter.on('event', () => {}); myEmitter.on('event', () => {}); console.log(listenerCount(myEmitter, 'event')); // Prints: 2 </code></pre> </section><section><h3><code>events.on(emitter, eventName[, options])</code><span><a class="mark" href="#eventsonemitter-eventname-options" id="eventsonemitter-eventname-options">#</a></span><a aria-hidden="true" class="legacy" id="events_events_on_emitter_eventname_options"></a></h3> <div class="api_metadata"> <span>Added in: v13.6.0, v12.16.0</span> </div><ul> <li><code>emitter</code> <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> <li><code>eventName</code> {string|symbol} The name of the event being listened for</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Can be used to cancel awaiting events.</li> </ul> </li> <li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> that iterates <code>eventName</code> events emitted by the <code>emitter</code></li> </ul> <pre><code class="language-mjs">import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here </code></pre> <pre><code class="language-cjs">const { on, EventEmitter } = require('node:events'); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); </code></pre> <p>Returns an <code>AsyncIterator</code> that iterates <code>eventName</code> events. It will throw if the <code>EventEmitter</code> emits <code>'error'</code>. It removes all listeners when exiting the loop. The <code>value</code> returned by each iteration is an array composed of the emitted event arguments.</p> <p>An <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> can be used to cancel waiting on events:</p> <pre><code class="language-mjs">import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort()); </code></pre> <pre><code class="language-cjs">const { on, EventEmitter } = require('node:events'); const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort()); </code></pre> </section><section><h3><code>events.setMaxListeners(n[, ...eventTargets])</code><span><a class="mark" href="#eventssetmaxlistenersn-eventtargets" id="eventssetmaxlistenersn-eventtargets">#</a></span><a aria-hidden="true" class="legacy" id="events_events_setmaxlisteners_n_eventtargets"></a></h3> <div class="api_metadata"> <span>Added in: v15.4.0</span> </div><ul> <li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A non-negative number. The maximum number of listeners per <code>EventTarget</code> event.</li> <li><code>...eventsTargets</code> {EventTarget[]|EventEmitter[]} Zero or more <a href="events.html#class-eventtarget" class="type"><EventTarget></a> or <a href="events.html#class-eventemitter" class="type"><EventEmitter></a> instances. If none are specified, <code>n</code> is set as the default max for all newly created <a href="events.html#class-eventtarget" class="type"><EventTarget></a> and <a href="events.html#class-eventemitter" class="type"><EventEmitter></a> objects.</li> </ul> <pre><code class="language-mjs">import { setMaxListeners, EventEmitter } from 'node:events'; const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter); </code></pre> <pre><code class="language-cjs">const { setMaxListeners, EventEmitter, } = require('node:events'); const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter); </code></pre> </section><section><h3><code>events.addAbortListener(signal, resource)</code><span><a class="mark" href="#eventsaddabortlistenersignal-resource" id="eventsaddabortlistenersignal-resource">#</a></span><a aria-hidden="true" class="legacy" id="events_events_addabortlistener_signal_resource"></a></h3> <div class="api_metadata"> <span>Added in: v18.18.0</span> </div><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> <li><code>listener</code> {Function|EventListener}</li> <li>Returns: <a href="https://tc39.es/proposal-explicit-resource-management/#sec-disposable-interface" class="type"><Disposable></a> that removes the <code>abort</code> listener.</li> </ul> <p>Listens once to the <code>abort</code> event on the provided <code>signal</code>.</p> <p>Listening to the <code>abort</code> event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call <a href="#eventstopimmediatepropagation"><code>e.stopImmediatePropagation()</code></a>. Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.</p> <p>This API allows safely using <code>AbortSignal</code>s in Node.js APIs by solving these two issues by listening to the event such that <code>stopImmediatePropagation</code> does not prevent the listener from running.</p> <p>Returns a disposable so that it may be unsubscribed from more easily.</p> <pre><code class="language-cjs">const { addAbortListener } = require('node:events'); function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } } </code></pre> <pre><code class="language-mjs">import { addAbortListener } from 'node:events'; function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } } </code></pre> </section><section><h3>Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code><span><a class="mark" href="#class-eventseventemitterasyncresource-extends-eventemitter" id="class-eventseventemitterasyncresource-extends-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_class_events_eventemitterasyncresource_extends_eventemitter"></a></h3> <div class="api_metadata"> <span>Added in: v17.4.0, v16.14.0</span> </div><p>Integrates <code>EventEmitter</code> with <a href="async_hooks.html#class-asyncresource" class="type"><AsyncResource></a> for <code>EventEmitter</code>s that require manual async tracking. Specifically, all events emitted by instances of <code>events.EventEmitterAsyncResource</code> will run within its <a href="async_context.html">async context</a>.</p> <pre><code class="language-mjs">import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; import { notStrictEqual, strictEqual } from 'node:assert'; import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); // 'foo' listeners will run in the EventEmitters async context. ee1.on('foo', () => { strictEqual(executionAsyncId(), ee1.asyncId); strictEqual(triggerAsyncId(), ee1.triggerAsyncId); }); const ee2 = new EventEmitter(); // 'foo' listeners on ordinary EventEmitters that do not track async // context, however, run in the same async context as the emit(). ee2.on('foo', () => { notStrictEqual(executionAsyncId(), ee2.asyncId); notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); }); Promise.resolve().then(() => { ee1.emit('foo'); ee2.emit('foo'); }); </code></pre> <pre><code class="language-cjs">const { EventEmitterAsyncResource, EventEmitter } = require('node:events'); const { notStrictEqual, strictEqual } = require('node:assert'); const { executionAsyncId, triggerAsyncId } = require('node:async_hooks'); // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); // 'foo' listeners will run in the EventEmitters async context. ee1.on('foo', () => { strictEqual(executionAsyncId(), ee1.asyncId); strictEqual(triggerAsyncId(), ee1.triggerAsyncId); }); const ee2 = new EventEmitter(); // 'foo' listeners on ordinary EventEmitters that do not track async // context, however, run in the same async context as the emit(). ee2.on('foo', () => { notStrictEqual(executionAsyncId(), ee2.asyncId); notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); }); Promise.resolve().then(() => { ee1.emit('foo'); ee2.emit('foo'); }); </code></pre> <p>The <code>EventEmitterAsyncResource</code> class has the same methods and takes the same options as <code>EventEmitter</code> and <code>AsyncResource</code> themselves.</p> <h4><code>new events.EventEmitterAsyncResource([options])</code><span><a class="mark" href="#new-eventseventemitterasyncresourceoptions" id="new-eventseventemitterasyncresourceoptions">#</a></span><a aria-hidden="true" class="legacy" id="events_new_events_eventemitterasyncresource_options"></a></h4> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>captureRejections</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> It enables <a href="#capture-rejections-of-promises">automatic capturing of promise rejection</a>. <strong>Default:</strong> <code>false</code>.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of async event. <strong>Default:</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target"><code>new.target.name</code></a>.</li> <li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the execution context that created this async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li> <li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code> when the object is garbage collected. This usually does not need to be set (even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code> is retrieved and the sensitive API's <code>emitDestroy</code> is called with it. When set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection will only take place if there is at least one active <code>destroy</code> hook. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <h4><code>eventemitterasyncresource.asyncId</code><span><a class="mark" href="#eventemitterasyncresourceasyncid" id="eventemitterasyncresourceasyncid">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_asyncid"></a></h4> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique <code>asyncId</code> assigned to the resource.</li> </ul> <h4><code>eventemitterasyncresource.asyncResource</code><span><a class="mark" href="#eventemitterasyncresourceasyncresource" id="eventemitterasyncresourceasyncresource">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_asyncresource"></a></h4> <ul> <li>Type: The underlying <a href="async_hooks.html#class-asyncresource" class="type"><AsyncResource></a>.</li> </ul> <p>The returned <code>AsyncResource</code> object has an additional <code>eventEmitter</code> property that provides a reference to this <code>EventEmitterAsyncResource</code>.</p> <h4><code>eventemitterasyncresource.emitDestroy()</code><span><a class="mark" href="#eventemitterasyncresourceemitdestroy" id="eventemitterasyncresourceemitdestroy">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_emitdestroy"></a></h4> <p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will be thrown if it is called more than once. This <strong>must</strong> be manually called. If the resource is left to be collected by the GC then the <code>destroy</code> hooks will never be called.</p> <h4><code>eventemitterasyncresource.triggerAsyncId</code><span><a class="mark" href="#eventemitterasyncresourcetriggerasyncid" id="eventemitterasyncresourcetriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_triggerasyncid"></a></h4> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The same <code>triggerAsyncId</code> that is passed to the <code>AsyncResource</code> constructor.</li> </ul> <p><a id="event-target-and-event-api"></a></p> </section><section><h3><code>EventTarget</code> and <code>Event</code> API<span><a class="mark" href="#eventtarget-and-event-api" id="eventtarget-and-event-api">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_and_event_api"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.0.0</td> <td><p>changed EventTarget error handling.</p> </td></tr> <tr><td>v15.4.0</td> <td><p>No longer experimental.</p> </td></tr> <tr><td>v15.0.0</td> <td><p>The <code>EventTarget</code> and <code>Event</code> classes are now available as globals.</p> </td></tr> <tr><td>v14.5.0</td> <td><p><span>Added in: v14.5.0</span></p> </td></tr> </table> </details> </div><p>The <code>EventTarget</code> and <code>Event</code> objects are a Node.js-specific implementation of the <a href="https://dom.spec.whatwg.org/#eventtarget"><code>EventTarget</code> Web API</a> that are exposed by some Node.js core APIs.</p> <pre><code class="language-js">const target = new EventTarget(); target.addEventListener('foo', (event) => { console.log('foo event happened!'); }); </code></pre> <h4>Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code><span><a class="mark" href="#nodejs-eventtarget-vs-dom-eventtarget" id="nodejs-eventtarget-vs-dom-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_node_js_eventtarget_vs_dom_eventtarget"></a></h4> <p>There are two key differences between the Node.js <code>EventTarget</code> and the <a href="https://dom.spec.whatwg.org/#eventtarget"><code>EventTarget</code> Web API</a>:</p> <ol> <li>Whereas DOM <code>EventTarget</code> instances <em>may</em> be hierarchical, there is no concept of hierarchy and event propagation in Node.js. That is, an event dispatched to an <code>EventTarget</code> does not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event.</li> <li>In the Node.js <code>EventTarget</code>, if an event listener is an async function or returns a <code>Promise</code>, and the returned <code>Promise</code> rejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (see <a href="#eventtarget-error-handling"><code>EventTarget</code> error handling</a> for details).</li> </ol> <h4><code>NodeEventTarget</code> vs. <code>EventEmitter</code><span><a class="mark" href="#nodeeventtarget-vs-eventemitter" id="nodeeventtarget-vs-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_vs_eventemitter"></a></h4> <p>The <code>NodeEventTarget</code> object implements a modified subset of the <code>EventEmitter</code> API that allows it to closely <em>emulate</em> an <code>EventEmitter</code> in certain situations. A <code>NodeEventTarget</code> is <em>not</em> an instance of <code>EventEmitter</code> and cannot be used in place of an <code>EventEmitter</code> in most cases.</p> <ol> <li>Unlike <code>EventEmitter</code>, any given <code>listener</code> can be registered at most once per event <code>type</code>. Attempts to register a <code>listener</code> multiple times are ignored.</li> <li>The <code>NodeEventTarget</code> does not emulate the full <code>EventEmitter</code> API. Specifically the <code>prependListener()</code>, <code>prependOnceListener()</code>, <code>rawListeners()</code>, and <code>errorMonitor</code> APIs are not emulated. The <code>'newListener'</code> and <code>'removeListener'</code> events will also not be emitted.</li> <li>The <code>NodeEventTarget</code> does not implement any special default behavior for events with type <code>'error'</code>.</li> <li>The <code>NodeEventTarget</code> supports <code>EventListener</code> objects as well as functions as handlers for all event types.</li> </ol> <h4>Event listener<span><a class="mark" href="#event-listener" id="event-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_listener"></a></h4> <p>Event listeners registered for an event <code>type</code> may either be JavaScript functions or objects with a <code>handleEvent</code> property whose value is a function.</p> <p>In either case, the handler function is invoked with the <code>event</code> argument passed to the <code>eventTarget.dispatchEvent()</code> function.</p> <p>Async functions may be used as event listeners. If an async handler function rejects, the rejection is captured and handled as described in <a href="#eventtarget-error-handling"><code>EventTarget</code> error handling</a>.</p> <p>An error thrown by one handler function does not prevent the other handlers from being invoked.</p> <p>The return value of a handler function is ignored.</p> <p>Handlers are always invoked in the order they were added.</p> <p>Handler functions may mutate the <code>event</code> object.</p> <pre><code class="language-js">function handler1(event) { console.log(event.type); // Prints 'foo' event.a = 1; } async function handler2(event) { console.log(event.type); // Prints 'foo' console.log(event.a); // Prints 1 } const handler3 = { handleEvent(event) { console.log(event.type); // Prints 'foo' }, }; const handler4 = { async handleEvent(event) { console.log(event.type); // Prints 'foo' }, }; const target = new EventTarget(); target.addEventListener('foo', handler1); target.addEventListener('foo', handler2); target.addEventListener('foo', handler3); target.addEventListener('foo', handler4, { once: true }); </code></pre> <h4><code>EventTarget</code> error handling<span><a class="mark" href="#eventtarget-error-handling" id="eventtarget-error-handling">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_error_handling"></a></h4> <p>When a registered event listener throws (or returns a Promise that rejects), by default the error is treated as an uncaught exception on <code>process.nextTick()</code>. This means uncaught exceptions in <code>EventTarget</code>s will terminate the Node.js process by default.</p> <p>Throwing within an event listener will <em>not</em> stop the other registered handlers from being invoked.</p> <p>The <code>EventTarget</code> does not implement any special default handling for <code>'error'</code> type events like <code>EventEmitter</code>.</p> <p>Currently errors are first forwarded to the <code>process.on('error')</code> event before reaching <code>process.on('uncaughtException')</code>. This behavior is deprecated and will change in a future release to align <code>EventTarget</code> with other Node.js APIs. Any code relying on the <code>process.on('error')</code> event should be aligned with the new behavior.</p> <h4>Class: <code>Event</code><span><a class="mark" href="#class-event" id="class-event">#</a></span><a aria-hidden="true" class="legacy" id="events_class_event"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v15.0.0</td> <td><p>The <code>Event</code> class is now available through the global object.</p> </td></tr> <tr><td>v14.5.0</td> <td><p><span>Added in: v14.5.0</span></p> </td></tr> </table> </details> </div><p>The <code>Event</code> object is an adaptation of the <a href="https://dom.spec.whatwg.org/#event"><code>Event</code> Web API</a>. Instances are created internally by Node.js.</p> <h5><code>event.bubbles</code><span><a class="mark" href="#eventbubbles" id="eventbubbles">#</a></span><a aria-hidden="true" class="legacy" id="events_event_bubbles"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Always returns <code>false</code>.</li> </ul> <p>This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.cancelBubble</code><span><a class="mark" href="#eventcancelbubble" id="eventcancelbubble">#</a></span><a aria-hidden="true" class="legacy" id="events_event_cancelbubble"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><blockquote> <p>Stability: 3 - Legacy: Use <a href="#eventstoppropagation"><code>event.stopPropagation()</code></a> instead.</p> </blockquote> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Alias for <code>event.stopPropagation()</code> if set to <code>true</code>. This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.cancelable</code><span><a class="mark" href="#eventcancelable" id="eventcancelable">#</a></span><a aria-hidden="true" class="legacy" id="events_event_cancelable"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> True if the event was created with the <code>cancelable</code> option.</li> </ul> <h5><code>event.composed</code><span><a class="mark" href="#eventcomposed" id="eventcomposed">#</a></span><a aria-hidden="true" class="legacy" id="events_event_composed"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Always returns <code>false</code>.</li> </ul> <p>This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.composedPath()</code><span><a class="mark" href="#eventcomposedpath" id="eventcomposedpath">#</a></span><a aria-hidden="true" class="legacy" id="events_event_composedpath"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><p>Returns an array containing the current <code>EventTarget</code> as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.currentTarget</code><span><a class="mark" href="#eventcurrenttarget" id="eventcurrenttarget">#</a></span><a aria-hidden="true" class="legacy" id="events_event_currenttarget"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> The <code>EventTarget</code> dispatching the event.</li> </ul> <p>Alias for <code>event.target</code>.</p> <h5><code>event.defaultPrevented</code><span><a class="mark" href="#eventdefaultprevented" id="eventdefaultprevented">#</a></span><a aria-hidden="true" class="legacy" id="events_event_defaultprevented"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if <code>cancelable</code> is <code>true</code> and <code>event.preventDefault()</code> has been called.</p> <h5><code>event.eventPhase</code><span><a class="mark" href="#eventeventphase" id="eventeventphase">#</a></span><a aria-hidden="true" class="legacy" id="events_event_eventphase"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Returns <code>0</code> while an event is not being dispatched, <code>2</code> while it is being dispatched.</li> </ul> <p>This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.isTrusted</code><span><a class="mark" href="#eventistrusted" id="eventistrusted">#</a></span><a aria-hidden="true" class="legacy" id="events_event_istrusted"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> <code>"abort"</code> event is emitted with <code>isTrusted</code> set to <code>true</code>. The value is <code>false</code> in all other cases.</p> <h5><code>event.preventDefault()</code><span><a class="mark" href="#eventpreventdefault" id="eventpreventdefault">#</a></span><a aria-hidden="true" class="legacy" id="events_event_preventdefault"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><p>Sets the <code>defaultPrevented</code> property to <code>true</code> if <code>cancelable</code> is <code>true</code>.</p> <h5><code>event.returnValue</code><span><a class="mark" href="#eventreturnvalue" id="eventreturnvalue">#</a></span><a aria-hidden="true" class="legacy" id="events_event_returnvalue"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><blockquote> <p>Stability: 3 - Legacy: Use <a href="#eventdefaultprevented"><code>event.defaultPrevented</code></a> instead.</p> </blockquote> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> True if the event has not been canceled.</li> </ul> <p>The value of <code>event.returnValue</code> is always the opposite of <code>event.defaultPrevented</code>. This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.srcElement</code><span><a class="mark" href="#eventsrcelement" id="eventsrcelement">#</a></span><a aria-hidden="true" class="legacy" id="events_event_srcelement"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><blockquote> <p>Stability: 3 - Legacy: Use <a href="#eventtarget"><code>event.target</code></a> instead.</p> </blockquote> <ul> <li>Type: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> The <code>EventTarget</code> dispatching the event.</li> </ul> <p>Alias for <code>event.target</code>.</p> <h5><code>event.stopImmediatePropagation()</code><span><a class="mark" href="#eventstopimmediatepropagation" id="eventstopimmediatepropagation">#</a></span><a aria-hidden="true" class="legacy" id="events_event_stopimmediatepropagation"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><p>Stops the invocation of event listeners after the current one completes.</p> <h5><code>event.stopPropagation()</code><span><a class="mark" href="#eventstoppropagation" id="eventstoppropagation">#</a></span><a aria-hidden="true" class="legacy" id="events_event_stoppropagation"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><p>This is not used in Node.js and is provided purely for completeness.</p> <h5><code>event.target</code><span><a class="mark" href="#eventtarget" id="eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_event_target"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> The <code>EventTarget</code> dispatching the event.</li> </ul> <h5><code>event.timeStamp</code><span><a class="mark" href="#eventtimestamp" id="eventtimestamp">#</a></span><a aria-hidden="true" class="legacy" id="events_event_timestamp"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The millisecond timestamp when the <code>Event</code> object was created.</p> <h5><code>event.type</code><span><a class="mark" href="#eventtype" id="eventtype">#</a></span><a aria-hidden="true" class="legacy" id="events_event_type"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The event type identifier.</p> <h4>Class: <code>EventTarget</code><span><a class="mark" href="#class-eventtarget" id="class-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_class_eventtarget"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v15.0.0</td> <td><p>The <code>EventTarget</code> class is now available through the global object.</p> </td></tr> <tr><td>v14.5.0</td> <td><p><span>Added in: v14.5.0</span></p> </td></tr> </table> </details> </div><h5><code>eventTarget.addEventListener(type, listener[, options])</code><span><a class="mark" href="#eventtargetaddeventlistenertype-listener-options" id="eventtargetaddeventlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_addeventlistener_type_listener_options"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v15.4.0</td> <td><p>add support for <code>signal</code> option.</p> </td></tr> <tr><td>v14.5.0</td> <td><p><span>Added in: v14.5.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>listener</code> {Function|EventListener}</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>once</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the listener is automatically removed when it is first invoked. <strong>Default:</strong> <code>false</code>.</li> <li><code>passive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, serves as a hint that the listener will not call the <code>Event</code> object's <code>preventDefault()</code> method. <strong>Default:</strong> <code>false</code>.</li> <li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Not directly used by Node.js. Added for API completeness. <strong>Default:</strong> <code>false</code>.</li> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> The listener will be removed when the given AbortSignal object's <code>abort()</code> method is called.</li> </ul> </li> </ul> <p>Adds a new handler for the <code>type</code> event. Any given <code>listener</code> is added only once per <code>type</code> and per <code>capture</code> option value.</p> <p>If the <code>once</code> option is <code>true</code>, the <code>listener</code> is removed after the next time a <code>type</code> event is dispatched.</p> <p>The <code>capture</code> option is not used by Node.js in any functional way other than tracking registered event listeners per the <code>EventTarget</code> specification. Specifically, the <code>capture</code> option is used as part of the key when registering a <code>listener</code>. Any individual <code>listener</code> may be added once with <code>capture = false</code>, and once with <code>capture = true</code>.</p> <pre><code class="language-js">function handler(event) {} const target = new EventTarget(); target.addEventListener('foo', handler, { capture: true }); // first target.addEventListener('foo', handler, { capture: false }); // second // Removes the second instance of handler target.removeEventListener('foo', handler); // Removes the first instance of handler target.removeEventListener('foo', handler, { capture: true }); </code></pre> <h5><code>eventTarget.dispatchEvent(event)</code><span><a class="mark" href="#eventtargetdispatcheventevent" id="eventtargetdispatcheventevent">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_dispatchevent_event"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><code>event</code> <a href="events.html#class-event" class="type"><Event></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if either event's <code>cancelable</code> attribute value is false or its <code>preventDefault()</code> method was not invoked, otherwise <code>false</code>.</li> </ul> <p>Dispatches the <code>event</code> to the list of handlers for <code>event.type</code>.</p> <p>The registered event listeners is synchronously invoked in the order they were registered.</p> <h5><code>eventTarget.removeEventListener(type, listener[, options])</code><span><a class="mark" href="#eventtargetremoveeventlistenertype-listener-options" id="eventtargetremoveeventlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_removeeventlistener_type_listener_options"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>listener</code> {Function|EventListener}</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> </li> </ul> <p>Removes the <code>listener</code> from the list of handlers for event <code>type</code>.</p> <h4>Class: <code>CustomEvent</code><span><a class="mark" href="#class-customevent" id="class-customevent">#</a></span><a aria-hidden="true" class="legacy" id="events_class_customevent"></a></h4> <div class="api_metadata"> <span>Added in: v18.7.0</span> </div><blockquote> <p>Stability: 1 - Experimental.</p> </blockquote> <ul> <li>Extends: <a href="events.html#class-event" class="type"><Event></a></li> </ul> <p>The <code>CustomEvent</code> object is an adaptation of the <a href="https://dom.spec.whatwg.org/#customevent"><code>CustomEvent</code> Web API</a>. Instances are created internally by Node.js.</p> <h5><code>event.detail</code><span><a class="mark" href="#eventdetail" id="eventdetail">#</a></span><a aria-hidden="true" class="legacy" id="events_event_detail"></a></h5> <div class="api_metadata"> <span>Added in: v18.7.0</span> </div><blockquote> <p>Stability: 1 - Experimental.</p> </blockquote> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Returns custom data passed when initializing.</li> </ul> <p>Read-only.</p> <h4>Class: <code>NodeEventTarget</code><span><a class="mark" href="#class-nodeeventtarget" id="class-nodeeventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_class_nodeeventtarget"></a></h4> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Extends: <a href="events.html#class-eventtarget" class="type"><EventTarget></a></li> </ul> <p>The <code>NodeEventTarget</code> is a Node.js-specific extension to <code>EventTarget</code> that emulates a subset of the <code>EventEmitter</code> API.</p> <h5><code>nodeEventTarget.addListener(type, listener)</code><span><a class="mark" href="#nodeeventtargetaddlistenertype-listener" id="nodeeventtargetaddlistenertype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_addlistener_type_listener"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p><code>listener</code> {Function|EventListener}</p> </li> <li><p>Returns: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> this</p> </li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that emulates the equivalent <code>EventEmitter</code> API. The only difference between <code>addListener()</code> and <code>addEventListener()</code> is that <code>addListener()</code> will return a reference to the <code>EventTarget</code>.</p> <h5><code>nodeEventTarget.emit(type, arg)</code><span><a class="mark" href="#nodeeventtargetemittype-arg" id="nodeeventtargetemittype-arg">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_emit_type_arg"></a></h5> <div class="api_metadata"> <span>Added in: v15.2.0</span> </div><ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>arg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if event listeners registered for the <code>type</code> exist, otherwise <code>false</code>.</li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that dispatches the <code>arg</code> to the list of handlers for <code>type</code>.</p> <h5><code>nodeEventTarget.eventNames()</code><span><a class="mark" href="#nodeeventtargeteventnames" id="nodeeventtargeteventnames">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_eventnames"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that returns an array of event <code>type</code> names for which event listeners are registered.</p> <h5><code>nodeEventTarget.listenerCount(type)</code><span><a class="mark" href="#nodeeventtargetlistenercounttype" id="nodeeventtargetlistenercounttype">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_listenercount_type"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></p> </li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that returns the number of event listeners registered for the <code>type</code>.</p> <h5><code>nodeEventTarget.setMaxListeners(n)</code><span><a class="mark" href="#nodeeventtargetsetmaxlistenersn" id="nodeeventtargetsetmaxlistenersn">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_setmaxlisteners_n"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that sets the number of max event listeners as <code>n</code>.</p> <h5><code>nodeEventTarget.getMaxListeners()</code><span><a class="mark" href="#nodeeventtargetgetmaxlisteners" id="nodeeventtargetgetmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_getmaxlisteners"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that returns the number of max event listeners.</p> <h5><code>nodeEventTarget.off(type, listener[, options])</code><span><a class="mark" href="#nodeeventtargetofftype-listener-options" id="nodeeventtargetofftype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_off_type_listener_options"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p><code>listener</code> {Function|EventListener}</p> </li> <li><p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> </li> <li><p>Returns: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> this</p> </li> </ul> <p>Node.js-specific alias for <code>eventTarget.removeEventListener()</code>.</p> <h5><code>nodeEventTarget.on(type, listener)</code><span><a class="mark" href="#nodeeventtargetontype-listener" id="nodeeventtargetontype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_on_type_listener"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p><code>listener</code> {Function|EventListener}</p> </li> <li><p>Returns: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> this</p> </li> </ul> <p>Node.js-specific alias for <code>eventTarget.addEventListener()</code>.</p> <h5><code>nodeEventTarget.once(type, listener)</code><span><a class="mark" href="#nodeeventtargetoncetype-listener" id="nodeeventtargetoncetype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_once_type_listener"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p><code>listener</code> {Function|EventListener}</p> </li> <li><p>Returns: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> this</p> </li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that adds a <code>once</code> listener for the given event <code>type</code>. This is equivalent to calling <code>on</code> with the <code>once</code> option set to <code>true</code>.</p> <h5><code>nodeEventTarget.removeAllListeners([type])</code><span><a class="mark" href="#nodeeventtargetremovealllistenerstype" id="nodeeventtargetremovealllistenerstype">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removealllisteners_type"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p>Returns: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> this</p> </li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class. If <code>type</code> is specified, removes all registered listeners for <code>type</code>, otherwise removes all registered listeners.</p> <h5><code>nodeEventTarget.removeListener(type, listener[, options])</code><span><a class="mark" href="#nodeeventtargetremovelistenertype-listener-options" id="nodeeventtargetremovelistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removelistener_type_listener_options"></a></h5> <div class="api_metadata"> <span>Added in: v14.5.0</span> </div><ul> <li><p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> </li> <li><p><code>listener</code> {Function|EventListener}</p> </li> <li><p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> </li> <li><p>Returns: <a href="events.html#class-eventtarget" class="type"><EventTarget></a> this</p> </li> </ul> <p>Node.js-specific extension to the <code>EventTarget</code> class that removes the <code>listener</code> for the given <code>type</code>. The only difference between <code>removeListener()</code> and <code>removeEventListener()</code> is that <code>removeListener()</code> will return a reference to the <code>EventTarget</code>.</p> </section> <!-- API END --> </div> </div> </div> </body> </html>