%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="v16.16.0"> <title>Events | Node.js v16.16.0 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <link rel="canonical" href="https://nodejs.org/api/events.html"> </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="/" 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>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="policy.html" class="nav-policy">Policies</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="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="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 v16.16.0 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="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><span class="stability_2"><a href="#events">Events</a></span> <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"><code>emitter.listenerCount(eventName)</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="#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><span class="stability_0"><a href="#eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a></span></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="#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"><code>eventTarget.removeEventListener(type, listener)</code></a></li> </ul> </li> <li><a href="#class-nodeeventtarget">Class: <code>NodeEventTarget</code></a> <ul> <li><a href="#nodeeventtargetaddlistenertype-listener-options"><code>nodeEventTarget.addListener(type, listener[, options])</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="#nodeeventtargetofftype-listener"><code>nodeEventTarget.off(type, listener)</code></a></li> <li><a href="#nodeeventtargetontype-listener-options"><code>nodeEventTarget.on(type, listener[, options])</code></a></li> <li><a href="#nodeeventtargetoncetype-listener-options"><code>nodeEventTarget.once(type, listener[, options])</code></a></li> <li><a href="#nodeeventtargetremovealllistenerstype"><code>nodeEventTarget.removeAllListeners([type])</code></a></li> <li><a href="#nodeeventtargetremovelistenertype-listener"><code>nodeEventTarget.removeListener(type, listener)</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>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="policy.html" class="nav-policy">Policies</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="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="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</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 <b>LTS</b></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 <b>LTS</b></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><span class="stability_2"><a href="#events">Events</a></span> <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"><code>emitter.listenerCount(eventName)</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="#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><span class="stability_0"><a href="#eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a></span></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="#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"><code>eventTarget.removeEventListener(type, listener)</code></a></li> </ul> </li> <li><a href="#class-nodeeventtarget">Class: <code>NodeEventTarget</code></a> <ul> <li><a href="#nodeeventtargetaddlistenertype-listener-options"><code>nodeEventTarget.addListener(type, listener[, options])</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="#nodeeventtargetofftype-listener"><code>nodeEventTarget.off(type, listener)</code></a></li> <li><a href="#nodeeventtargetontype-listener-options"><code>nodeEventTarget.on(type, listener[, options])</code></a></li> <li><a href="#nodeeventtargetoncetype-listener-options"><code>nodeEventTarget.once(type, listener[, options])</code></a></li> <li><a href="#nodeeventtargetremovealllistenerstype"><code>nodeEventTarget.removeAllListeners([type])</code></a></li> <li><a href="#nodeeventtargetremovelistenertype-listener"><code>nodeEventTarget.removeListener(type, listener)</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> <p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p> <p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v16.16.0/lib/events.js">lib/events.js</a></p> <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-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {} <span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'an event occurred!'</span>); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);</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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>, <span class="hljs-variable language_">this</span> === myEmitter); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// a b MyEmitter {</span> <span class="hljs-comment">// domain: null,</span> <span class="hljs-comment">// _events: { event: [Function] },</span> <span class="hljs-comment">// _eventsCount: 1,</span> <span class="hljs-comment">// _maxListeners: undefined } true</span> }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>); <span class="hljs-comment">// Prints: a b {}</span> }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> { <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this happens asynchronously'</span>); }); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); <span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>; myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Prints: 1</span> myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Prints: 2</span></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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); <span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>; myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Prints: 1</span> myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Ignored</span></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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>)); <span class="hljs-comment">// Throws and crashes Node.js</span></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>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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'whoops! there was an error'</span>); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>)); <span class="hljs-comment">// Prints: whoops! there was an error</span></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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, errorMonitor } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(errorMonitor, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { <span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">log</span>(err); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>)); <span class="hljs-comment">// Still throws and crashes Node.js</span></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-js"><span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>); });</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-js"><span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> }); ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>); }); ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>); <span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> }); ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>); }); ee2[<span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.rejection'</span>)] = <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>;</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-js"><span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); events.<span class="hljs-property">captureRejections</span> = <span class="hljs-literal">true</span>; <span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> events.<span class="hljs-title class_">EventEmitter</span>(); ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>); }); ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</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> <tbody><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> </tbody></table> </details> </div> <p>The <code>EventEmitter</code> class is defined and exposed by the <code>events</code> module:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);</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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {} <span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); <span class="hljs-comment">// Only do this once so we don't loop forever</span> myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'newListener'</span>, <span class="hljs-function">(<span class="hljs-params">event, listener</span>) =></span> { <span class="hljs-keyword">if</span> (event === <span class="hljs-string">'event'</span>) { <span class="hljs-comment">// Insert a new listener in front</span> myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>); }); } }); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>); }); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// B</span> <span class="hljs-comment">// A</span></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> <tbody><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> </tbody></table> </details> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-comment">// First listener</span> myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">firstListener</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Helloooo! first listener'</span>); }); <span class="hljs-comment">// Second listener</span> myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">secondListener</span>(<span class="hljs-params">arg1, arg2</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${arg1}</span>, <span class="hljs-subst">${arg2}</span> in second listener`</span>); }); <span class="hljs-comment">// Third listener</span> myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">thirdListener</span>(<span class="hljs-params">...args</span>) { <span class="hljs-keyword">const</span> parameters = args.<span class="hljs-title function_">join</span>(<span class="hljs-string">', '</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${parameters}</span> in third listener`</span>); }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEmitter.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'event'</span>)); myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// [</span> <span class="hljs-comment">// [Function: firstListener],</span> <span class="hljs-comment">// [Function: secondListener],</span> <span class="hljs-comment">// [Function: thirdListener]</span> <span class="hljs-comment">// ]</span> <span class="hljs-comment">// Helloooo! first listener</span> <span class="hljs-comment">// event with parameters 1, 2 in second listener</span> <span class="hljs-comment">// event with parameters 1, 2, 3, 4, 5 in third listener</span></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-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {}); myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'bar'</span>, <span class="hljs-function">() =></span> {}); <span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'symbol'</span>); myEE.<span class="hljs-title function_">on</span>(sym, <span class="hljs-function">() =></span> {}); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEE.<span class="hljs-title function_">eventNames</span>()); <span class="hljs-comment">// Prints: [ 'foo', 'bar', Symbol(symbol) ]</span></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)</code><span><a class="mark" href="#emitterlistenercounteventname" id="emitterlistenercounteventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listenercount_eventname"></a></h4> <div class="api_metadata"> <span>Added in: v3.2.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event being listened for</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 to the event named <code>eventName</code>.</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> <tbody><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> </tbody></table> </details> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>); }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(server.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'connection'</span>))); <span class="hljs-comment">// Prints: [ [Function] ]</span></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>); });</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-js"><span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>)); myEE.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>)); myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// b</span> <span class="hljs-comment">// a</span></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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.<span class="hljs-title function_">once</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Ah, we have our first user!'</span>); });</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-js"><span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); myEE.<span class="hljs-title function_">once</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>)); myEE.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>)); myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// b</span> <span class="hljs-comment">// a</span></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>); });</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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Ah, we have our first user!'</span>); });</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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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"><span class="hljs-keyword">const</span> <span class="hljs-title function_">callback</span> = (<span class="hljs-params">stream</span>) => { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>); }; server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, callback); <span class="hljs-comment">// ...</span> server.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'connection'</span>, 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-js"><span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>(); <span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackA</span> = (<span class="hljs-params"></span>) => { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>); myEmitter.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'event'</span>, callbackB); }; <span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackB</span> = (<span class="hljs-params"></span>) => { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>); }; myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackA); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackB); <span class="hljs-comment">// callbackA removes listener callbackB but it will still be called.</span> <span class="hljs-comment">// Internal listener array at time of emit [callbackA, callbackB]</span> myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// A</span> <span class="hljs-comment">// B</span> <span class="hljs-comment">// callbackB is now removed.</span> <span class="hljs-comment">// Internal listener array [callbackA]</span> myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// A</span></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-js"><span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-keyword">function</span> <span class="hljs-title function_">pong</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'pong'</span>); } ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ping'</span>, pong); ee.<span class="hljs-title function_">once</span>(<span class="hljs-string">'ping'</span>, pong); ee.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'ping'</span>, pong); ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>); ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);</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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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-js"><span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log once'</span>)); <span class="hljs-comment">// Returns a new Array with a function `onceWrapper` which has a property</span> <span class="hljs-comment">// `listener` which contains the original listener bound above</span> <span class="hljs-keyword">const</span> listeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>); <span class="hljs-keyword">const</span> logFnWrapper = listeners[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Logs "log once" to the console and does not unbind the `once` event</span> logFnWrapper.<span class="hljs-title function_">listener</span>(); <span class="hljs-comment">// Logs "log once" to the console and removes the listener</span> <span class="hljs-title function_">logFnWrapper</span>(); emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log persistently'</span>)); <span class="hljs-comment">// Will return a new Array with a single function bound by `.on()` above</span> <span class="hljs-keyword">const</span> newListeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>); <span class="hljs-comment">// Logs "log persistently" twice</span> newListeners[<span class="hljs-number">0</span>](); emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'log'</span>);</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> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>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> </tbody></table> </details> </div> <ul> <li><code>err</code> Error</li> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, captureRejectionSymbol } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> { <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">super</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> }); } [captureRejectionSymbol](err, event, ...args) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'rejection happened for'</span>, event, <span class="hljs-string">'with'</span>, err, ...args); <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err); } <span class="hljs-title function_">destroy</span>(<span class="hljs-params">err</span>) { <span class="hljs-comment">// Tear the resource down here.</span> } }</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-js">emitter.<span class="hljs-title function_">setMaxListeners</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() + <span class="hljs-number">1</span>); emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">// do stuff</span> emitter.<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() - <span class="hljs-number">1</span>, <span class="hljs-number">0</span>)); });</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</span> </div> <ul> <li><code>emitterOrTarget</code> <a href="events.html#class-eventemitter" class="type"><EventEmitter></a> | <a href="events.html#class-eventtarget" class="type"><EventTarget></a></li> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></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-js"><span class="hljs-keyword">const</span> { getEventListeners, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); { <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>); ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, listener); <span class="hljs-title function_">getEventListeners</span>(ee, <span class="hljs-string">'foo'</span>); <span class="hljs-comment">// [listener]</span> } { <span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>(); <span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>); et.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, listener); <span class="hljs-title function_">getEventListeners</span>(et, <span class="hljs-string">'foo'</span>); <span class="hljs-comment">// [listener]</span> }</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> <tbody><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> </tbody></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-js"><span class="hljs-keyword">const</span> { once, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'myevent'</span>, <span class="hljs-number">42</span>); }); <span class="hljs-keyword">const</span> [value] = <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value); <span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>); process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err); }); <span class="hljs-keyword">try</span> { <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>); } <span class="hljs-keyword">catch</span> (err) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'error happened'</span>, err); } } <span class="hljs-title function_">run</span>();</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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'error'</span>) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">[err]</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'ok'</span>, err.<span class="hljs-property">message</span>)) .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'error'</span>, err.<span class="hljs-property">message</span>)); ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom'</span>)); <span class="hljs-comment">// Prints: ok boom</span></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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">emitter, event, signal</span>) { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(emitter, event, { signal }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'event emitted!'</span>); } <span class="hljs-keyword">catch</span> (error) { <span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Waiting for the event was canceled!'</span>); } <span class="hljs-keyword">else</span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error'</span>, error.<span class="hljs-property">message</span>); } } } <span class="hljs-title function_">foo</span>(ee, <span class="hljs-string">'foo'</span>, ac.<span class="hljs-property">signal</span>); ac.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Abort waiting for the event</span> ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// Prints: Waiting for the event was canceled!</span></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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'bar'</span>); <span class="hljs-comment">// This Promise will never resolve because the 'foo' event will</span> <span class="hljs-comment">// have already been emitted before the Promise is created.</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>); } process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>); myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); }); <span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>), <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>)]); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>); } process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>); myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); }); <span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</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> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>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> </tbody></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> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>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> </tbody></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> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#stability-index">Stability: 0</a> - Deprecated: Use <a href="#emitterlistenercounteventname"><code>emitter.listenerCount()</code></a> instead.</div><p></p> <ul> <li><code>emitter</code> <a href="events.html#class-eventemitter" class="type"><EventEmitter></a> The emitter to query</li> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, listenerCount } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {}); myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {}); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">listenerCount</span>(myEmitter, <span class="hljs-string">'event'</span>)); <span class="hljs-comment">// Prints: 2</span></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> 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-js"><span class="hljs-keyword">const</span> { on, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); (<span class="hljs-keyword">async</span> () => { <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-comment">// Emit later on</span> process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>); ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>); }); <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>)) { <span class="hljs-comment">// The execution of this inner block is synchronous and it</span> <span class="hljs-comment">// processes one event at a time (even with await). Do not use</span> <span class="hljs-comment">// if concurrent execution is required.</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span> } <span class="hljs-comment">// Unreachable here</span> })();</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-js"><span class="hljs-keyword">const</span> { on, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); (<span class="hljs-keyword">async</span> () => { <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-comment">// Emit later on</span> process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>); ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>); }); <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>, { <span class="hljs-attr">signal</span>: ac.<span class="hljs-property">signal</span> })) { <span class="hljs-comment">// The execution of this inner block is synchronous and it</span> <span class="hljs-comment">// processes one event at a time (even with await). Do not use</span> <span class="hljs-comment">// if concurrent execution is required.</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span> } <span class="hljs-comment">// Unreachable here</span> })(); process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());</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> <a href="events.html#class-eventtarget" class="type"><EventTarget[]></a> | <a href="events.html#class-eventemitter" class="type"><EventEmitter[]></a> 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-js"><span class="hljs-keyword">const</span> { setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>(); <span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">5</span>, target, emitter);</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: 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-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitterAsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); <span class="hljs-keyword">const</span> { notStrictEqual, strictEqual } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'assert'</span>); <span class="hljs-keyword">const</span> { executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>); <span class="hljs-comment">// Async tracking tooling will identify this as 'Q'.</span> <span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitterAsyncResource</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Q'</span> }); <span class="hljs-comment">// 'foo' listeners will run in the EventEmitters async context.</span> ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> { <span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee1.<span class="hljs-property">asyncId</span>); <span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee1.<span class="hljs-property">triggerAsyncId</span>); }); <span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); <span class="hljs-comment">// 'foo' listeners on ordinary EventEmitters that do not track async</span> <span class="hljs-comment">// context, however, run in the same async context as the emit().</span> ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> { <span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee2.<span class="hljs-property">asyncId</span>); <span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee2.<span class="hljs-property">triggerAsyncId</span>); }); <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> { ee1.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); ee2.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); });</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> <tbody><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> </tbody></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"><span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>(); target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo event happened!'</span>); });</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>, <code>setMaxListeners()</code>, <code>getMaxListeners()</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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">handler1</span>(<span class="hljs-params">event</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span> event.<span class="hljs-property">a</span> = <span class="hljs-number">1</span>; } <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">handler2</span>(<span class="hljs-params">event</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">a</span>); <span class="hljs-comment">// Prints 1</span> } <span class="hljs-keyword">const</span> handler3 = { <span class="hljs-title function_">handleEvent</span>(<span class="hljs-params">event</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span> } }; <span class="hljs-keyword">const</span> handler4 = { <span class="hljs-keyword">async</span> <span class="hljs-title function_">handleEvent</span>(<span class="hljs-params">event</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span> } }; <span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>(); target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler1); target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler2); target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler3); target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler4, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });</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> <tbody><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> </tbody></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> <p>Alias for <code>event.stopPropagation()</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> <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>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> <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> <tbody><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> </tbody></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"> <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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></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>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> </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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">handler</span>(<span class="hljs-params">event</span>) {} <span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>(); target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> }); <span class="hljs-comment">// first</span> target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">false</span> }); <span class="hljs-comment">// second</span> <span class="hljs-comment">// Removes the second instance of handler</span> target.<span class="hljs-title function_">removeEventListener</span>(<span class="hljs-string">'foo'</span>, handler); <span class="hljs-comment">// Removes the first instance of handler</span> target.<span class="hljs-title function_">removeEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });</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)</code><span><a class="mark" href="#eventtargetremoveeventlistenertype-listener" id="eventtargetremoveeventlistenertype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_removeeventlistener_type_listener"></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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></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>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>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[, options])</code><span><a class="mark" href="#nodeeventtargetaddlistenertype-listener-options" id="nodeeventtargetaddlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_addlistener_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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></a></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>once</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 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.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.off(type, listener)</code><span><a class="mark" href="#nodeeventtargetofftype-listener" id="nodeeventtargetofftype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_off_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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></a></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.removeListener()</code>.</p> <h5><code>nodeEventTarget.on(type, listener[, options])</code><span><a class="mark" href="#nodeeventtargetontype-listener-options" id="nodeeventtargetontype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_on_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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></a></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>once</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.addListener()</code>.</p> <h5><code>nodeEventTarget.once(type, listener[, options])</code><span><a class="mark" href="#nodeeventtargetoncetype-listener-options" id="nodeeventtargetoncetype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_once_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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></a></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> </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)</code><span><a class="mark" href="#nodeeventtargetremovelistenertype-listener" id="nodeeventtargetremovelistenertype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removelistener_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> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="events.html#event-listener" class="type"><EventListener></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 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> <script> 'use strict'; { const kCustomPreference = 'customDarkTheme'; const userSettings = sessionStorage.getItem(kCustomPreference); const themeToggleButton = document.getElementById('theme-toggle-btn'); if (userSettings === null && window.matchMedia) { const mq = window.matchMedia('(prefers-color-scheme: dark)'); if ('onchange' in mq) { function mqChangeListener(e) { document.documentElement.classList.toggle('dark-mode', e.matches); } mq.addEventListener('change', mqChangeListener); if (themeToggleButton) { themeToggleButton.addEventListener('click', function() { mq.removeEventListener('change', mqChangeListener); }, { once: true }); } } if (mq.matches) { document.documentElement.classList.add('dark-mode'); } } else if (userSettings === 'true') { document.documentElement.classList.add('dark-mode'); } if (themeToggleButton) { themeToggleButton.hidden = false; themeToggleButton.addEventListener('click', function() { sessionStorage.setItem( kCustomPreference, document.documentElement.classList.toggle('dark-mode') ); }); } } </script> </body> </html>