{
  "source": "doc/api/events.markdown",
  "modules": [
    {
      "textRaw": "Events",
      "name": "Events",
      "stability": 2,
      "stabilityText": "Stable",
      "type": "module",
      "desc": "<p>Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called &quot;emitters&quot;)\nperiodically emit named events that cause Function objects (&quot;listeners&quot;) to be\ncalled.\n\n</p>\n<p>For instance: a [<code>net.Server</code>][] object emits an event each time a peer\nconnects to it; a [<code>fs.ReadStream</code>][] emits an event when the file is opened;\na [stream][] emits an event whenever data is available to be read.\n\n</p>\n<p>All objects that emit events are instances of the <code>EventEmitter</code> class. These\nobjects expose an <code>eventEmitter.on()</code> function that allows one or more\nFunctions to be attached to named events emitted by the object. Typically,\nevent names are camel-cased strings but any valid JavaScript property key\ncan be used.\n\n</p>\n<p>When the <code>EventEmitter</code> object emits an event, all of the Functions attached\nto that specific event are called <em>synchronously</em>. Any values returned by the\ncalled listeners are <em>ignored</em> and will be discarded.\n\n</p>\n<p>The following example shows a simple <code>EventEmitter</code> instance with a single\nlistener. The <code>eventEmitter.on()</code> method is used to register listeners, while\nthe <code>eventEmitter.emit()</code> method is used to trigger the event.\n\n</p>\n<pre><code>const EventEmitter = require(&#39;events&#39;);\nconst util = require(&#39;util&#39;);\n\nfunction MyEmitter() {\n  EventEmitter.call(this);\n}\nutil.inherits(MyEmitter, EventEmitter);\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on(&#39;event&#39;, function() {\n  console.log(&#39;an event occurred!&#39;);\n});\nmyEmitter.emit(&#39;event&#39;);</code></pre>\n<p>Any object can become an <code>EventEmitter</code> through inheritance. The example above\nuses the traditional Node.js style prototypical inheritance using\nthe <code>util.inherits()</code> method. It is, however, possible to use ES6 classes as\nwell:\n\n</p>\n<pre><code>const EventEmitter = require(&#39;events&#39;);\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on(&#39;event&#39;, function() {\n  console.log(&#39;an event occurred!&#39;);\n});\nmyEmitter.emit(&#39;event&#39;);</code></pre>\n",
      "modules": [
        {
          "textRaw": "Passing arguments and `this` to listeners",
          "name": "passing_arguments_and_`this`_to_listeners",
          "desc": "<p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be\npassed to the listener functions. It is important to keep in mind that when an\nordinary listener function is called by the <code>EventEmitter</code>, the standard <code>this</code>\nkeyword is intentionally set to reference the <code>EventEmitter</code> to which the\nlistener is attached.\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nmyEmitter.on(&#39;event&#39;, function(a, b) {\n  console.log(a, b, this);\n    // Prints:\n    //   a b MyEmitter {\n    //     domain: null,\n    //     _events: { event: [Function] },\n    //     _eventsCount: 1,\n    //     _maxListeners: undefined }\n});\nmyEmitter.emit(&#39;event&#39;, &#39;a&#39;, &#39;b&#39;);</code></pre>\n<p>It is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe <code>this</code> keyword will no longer reference the <code>EventEmitter</code> instance:\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nmyEmitter.on(&#39;event&#39;, (a, b) =&gt; {\n  console.log(a, b, this);\n    // Prints: a b {}\n});\nmyEmitter.emit(&#39;event&#39;, &#39;a&#39;, &#39;b&#39;);</code></pre>\n",
          "type": "module",
          "displayName": "Passing arguments and `this` to listeners"
        },
        {
          "textRaw": "Asynchronous vs. Synchronous",
          "name": "asynchronous_vs._synchronous",
          "desc": "<p>The <code>EventListener</code> calls all listeners synchronously in the order in which\nthey were registered. This is important to ensure the proper sequencing of\nevents and to avoid race conditions or logic errors. When appropriate,\nlistener functions can switch to an asynchronous mode of operation using\nthe <code>setImmediate()</code> or <code>process.nextTick()</code> methods:\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nmyEmitter.on(&#39;event&#39;, (a, b) =&gt; {\n  setImmediate(() =&gt; {\n    console.log(&#39;this happens asynchronously&#39;);\n  });\n});\nmyEmitter.emit(&#39;event&#39;, &#39;a&#39;, &#39;b&#39;);</code></pre>\n",
          "type": "module",
          "displayName": "Asynchronous vs. Synchronous"
        },
        {
          "textRaw": "Handling events only once",
          "name": "handling_events_only_once",
          "desc": "<p>When a listener is registered using the <code>eventEmitter.on()</code> method, that\nlistener will be invoked <em>every time</em> the named event is emitted.\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nvar m = 0;\nmyEmitter.on(&#39;event&#39;, () =&gt; {\n  console.log(++m);\n});\nmyEmitter.emit(&#39;event&#39;);\n  // Prints: 1\nmyEmitter.emit(&#39;event&#39;);\n  // Prints: 2</code></pre>\n<p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener\nthat is immediately unregistered after it is called.\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nvar m = 0;\nmyEmitter.once(&#39;event&#39;, () =&gt; {\n  console.log(++m);\n});\nmyEmitter.emit(&#39;event&#39;);\n  // Prints: 1\nmyEmitter.emit(&#39;event&#39;);\n  // Ignored</code></pre>\n",
          "type": "module",
          "displayName": "Handling events only once"
        },
        {
          "textRaw": "Error events",
          "name": "error_events",
          "desc": "<p>When an error occurs within an <code>EventEmitter</code> instance, the typical action is\nfor an <code>&#39;error&#39;</code> event to be emitted. These are treated as a special case\nwithin Node.js.\n\n</p>\n<p>If an <code>EventEmitter</code> does <em>not</em> have at least one listener registered for the\n<code>&#39;error&#39;</code> event, and an <code>&#39;error&#39;</code> event is emitted, the error is thrown, a\nstack trace is printed, and the Node.js process exits.\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nmyEmitter.emit(&#39;error&#39;, new Error(&#39;whoops!&#39;));\n  // Throws and crashes Node.js</code></pre>\n<p>To guard against crashing the Node.js process, developers can either register\na listener for the <code>process.on(&#39;uncaughtException&#39;)</code> event or use the\n[<code>domain</code>][] module (<em>Note, however, that the <code>domain</code> module has been\ndeprecated</em>).\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\n\nprocess.on(&#39;uncaughtException&#39;, (err) =&gt; {\n  console.log(&#39;whoops! there was an error&#39;);\n});\n\nmyEmitter.emit(&#39;error&#39;, new Error(&#39;whoops!&#39;));\n  // Prints: whoops! there was an error</code></pre>\n<p>As a best practice, developers should always register listeners for the\n<code>&#39;error&#39;</code> event:\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nmyEmitter.on(&#39;error&#39;, (err) =&gt; {\n  console.log(&#39;whoops! there was an error&#39;);\n});\nmyEmitter.emit(&#39;error&#39;, new Error(&#39;whoops!&#39;));\n  // Prints: whoops! there was an error</code></pre>\n",
          "type": "module",
          "displayName": "Error events"
        }
      ],
      "classes": [
        {
          "textRaw": "Class: EventEmitter",
          "type": "class",
          "name": "EventEmitter",
          "desc": "<p>The <code>EventEmitter</code> class is defined and exposed by the <code>events</code> module:\n\n</p>\n<pre><code>const EventEmitter = require(&#39;events&#39;);</code></pre>\n<p>All EventEmitters emit the event <code>&#39;newListener&#39;</code> when new listeners are\nadded and <code>&#39;removeListener&#39;</code> when a listener is removed.\n\n</p>\n",
          "events": [
            {
              "textRaw": "Event: 'newListener'",
              "type": "event",
              "name": "newListener",
              "params": [],
              "desc": "<p>The <code>EventEmitter</code> instance will emit it&#39;s own <code>&#39;newListener&#39;</code> event <em>before</em>\na listener is added to it&#39;s internal array of listeners.\n\n</p>\n<p>Listeners registered for the <code>&#39;newListener&#39;</code> event will be passed the event\nname and a reference to the listener being added.\n\n</p>\n<p>The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any <em>additional</em> listeners registered to the same\n<code>name</code> <em>within</em> the <code>&#39;newListener&#39;</code> callback will be inserted <em>before</em> the\nlistener that is in the process of being added.\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\n// Only do this once so we don&#39;t loop forever\nmyEmitter.once(&#39;newListener&#39;, (event, listener) =&gt; {\n  if (event === &#39;event&#39;) {\n    // Insert a new listener in front\n    myEmitter.on(&#39;event&#39;, () =&gt; {\n      console.log(&#39;B&#39;);\n    });\n  }\n});\nmyEmitter.on(&#39;event&#39;, () =&gt; {\n  console.log(&#39;A&#39;);\n});\nmyEmitter.emit(&#39;event&#39;);\n  // Prints:\n  //   B\n  //   A</code></pre>\n"
            },
            {
              "textRaw": "Event: 'removeListener'",
              "type": "event",
              "name": "removeListener",
              "params": [],
              "desc": "<p>The <code>&#39;removeListener&#39;</code> event is emitted <em>after</em> a listener is removed.\n\n</p>\n"
            }
          ],
          "methods": [
            {
              "textRaw": "EventEmitter.listenerCount(emitter, event)",
              "type": "method",
              "name": "listenerCount",
              "stability": 0,
              "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.",
              "desc": "<p>A class method that returns the number of listeners for the given <code>event</code>\nregistered on the given <code>emitter</code>.\n\n</p>\n<pre><code>const myEmitter = new MyEmitter();\nmyEmitter.on(&#39;event&#39;, () =&gt; {});\nmyEmitter.on(&#39;event&#39;, () =&gt; {});\nconsole.log(EventEmitter.listenerCount(myEmitter, &#39;event&#39;));\n  // Prints: 2</code></pre>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "emitter"
                    },
                    {
                      "name": "event"
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.addListener(event, listener)",
              "type": "method",
              "name": "addListener",
              "desc": "<p>Alias for <code>emitter.on(event, listener)</code>.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event"
                    },
                    {
                      "name": "listener"
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.emit(event[, arg1][, arg2][, ...])",
              "type": "method",
              "name": "emit",
              "desc": "<p>Synchronously calls each of the listeners registered for <code>event</code>, in the order\nthey were registered, passing the supplied arguments to each.\n\n</p>\n<p>Returns <code>true</code> if event had listeners, <code>false</code> otherwise.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event"
                    },
                    {
                      "name": "arg1",
                      "optional": true
                    },
                    {
                      "name": "arg2",
                      "optional": true
                    },
                    {
                      "name": "...",
                      "optional": true
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.getMaxListeners()",
              "type": "method",
              "name": "getMaxListeners",
              "desc": "<p>Returns the current max listener value for the <code>EventEmitter</code> which is either\nset by [<code>emitter.setMaxListeners(n)</code>][] or defaults to\n[<code>EventEmitter.defaultMaxListeners</code>][].\n\n</p>\n",
              "signatures": [
                {
                  "params": []
                }
              ]
            },
            {
              "textRaw": "emitter.listenerCount(event)",
              "type": "method",
              "name": "listenerCount",
              "signatures": [
                {
                  "params": [
                    {
                      "textRaw": "`event` {Value} The type of event ",
                      "name": "event",
                      "type": "Value",
                      "desc": "The type of event"
                    }
                  ]
                },
                {
                  "params": [
                    {
                      "name": "event"
                    }
                  ]
                }
              ],
              "desc": "<p>Returns the number of listeners listening to the <code>event</code> type.\n\n</p>\n"
            },
            {
              "textRaw": "emitter.listeners(event)",
              "type": "method",
              "name": "listeners",
              "desc": "<p>Returns a copy of the array of listeners for the specified <code>event</code>.\n\n</p>\n<pre><code>server.on(&#39;connection&#39;, (stream) =&gt; {\n  console.log(&#39;someone connected!&#39;);\n});\nconsole.log(util.inspect(server.listeners(&#39;connection&#39;)));\n  // Prints: [ [Function] ]</code></pre>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event"
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.on(event, listener)",
              "type": "method",
              "name": "on",
              "desc": "<p>Adds the <code>listener</code> function to the end of the listeners array for the\nspecified <code>event</code>. No checks are made to see if the <code>listener</code> has already\nbeen added. Multiple calls passing the same combination of <code>event</code> and\n<code>listener</code> will result in the <code>listener</code> being added, and called, multiple\ntimes.\n\n</p>\n<pre><code>server.on(&#39;connection&#39;, (stream) =&gt; {\n  console.log(&#39;someone connected!&#39;);\n});</code></pre>\n<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event"
                    },
                    {
                      "name": "listener"
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.once(event, listener)",
              "type": "method",
              "name": "once",
              "desc": "<p>Adds a <strong>one time</strong> <code>listener</code> function for the <code>event</code>. This listener is\ninvoked only the next time <code>event</code> is triggered, after which it is removed.\n\n</p>\n<pre><code>server.once(&#39;connection&#39;, (stream) =&gt; {\n  console.log(&#39;Ah, we have our first user!&#39;);\n});</code></pre>\n<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event"
                    },
                    {
                      "name": "listener"
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.removeAllListeners([event])",
              "type": "method",
              "name": "removeAllListeners",
              "desc": "<p>Removes all listeners, or those of the specified <code>event</code>.\n\n</p>\n<p>Note that it is bad practice to remove listeners added elsewhere in the code,\nparticularly when the <code>EventEmitter</code> instance was created by some other\ncomponent or module (e.g. sockets or file streams).\n\n</p>\n<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event",
                      "optional": true
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.removeListener(event, listener)",
              "type": "method",
              "name": "removeListener",
              "desc": "<p>Removes the specified <code>listener</code> from the listener array for the specified\n<code>event</code>.\n\n</p>\n<pre><code>var callback = function(stream) {\n  console.log(&#39;someone connected!&#39;);\n};\nserver.on(&#39;connection&#39;, callback);\n// ...\nserver.removeListener(&#39;connection&#39;, callback);</code></pre>\n<p><code>removeListener</code> will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified <code>event</code>, then <code>removeListener</code> must be called\nmultiple times to remove each instance.\n\n</p>\n<p>Because listeners are managed using an internal array, calling this will\nchange the position indices of any listener registered <em>after</em> the listener\nbeing removed. This will not impact the order in which listeners are called,\nbut it will means that any copies of the listener array as returned by\nthe <code>emitter.listeners()</code> method will need to be recreated.\n\n</p>\n<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "event"
                    },
                    {
                      "name": "listener"
                    }
                  ]
                }
              ]
            },
            {
              "textRaw": "emitter.setMaxListeners(n)",
              "type": "method",
              "name": "setMaxListeners",
              "desc": "<p>By default EventEmitters will print a warning if more than <code>10</code> listeners are\nadded for a particular event. This is a useful default that helps finding\nmemory leaks. Obviously, not all events should be limited to just 10 listeners.\nThe <code>emitter.setMaxListeners()</code> method allows the limit to be modified for this\nspecific <code>EventEmitter</code> instance. The value can be set to <code>Infinity</code> (or <code>0</code>)\nfor to indicate an unlimited number of listeners.\n\n</p>\n<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.\n\n</p>\n",
              "signatures": [
                {
                  "params": [
                    {
                      "name": "n"
                    }
                  ]
                }
              ]
            }
          ],
          "properties": [
            {
              "textRaw": "EventEmitter.defaultMaxListeners",
              "name": "defaultMaxListeners",
              "desc": "<p>By default, a maximum of <code>10</code> listeners can be registered for any single\nevent. This limit can be changed for individual <code>EventEmitter</code> instances\nusing the [<code>emitter.setMaxListeners(n)</code>][] method. To change the default\nfor <em>all</em> <code>EventEmitter</code> instances, the <code>EventEmitter.defaultMaxListeners</code>\nproperty can be used.\n\n</p>\n<p>Take caution when setting the <code>EventEmitter.defaultMaxListeners</code> because the\nchange effects <em>all</em> <code>EventEmitter</code> instances, including those created before\nthe change is made. However, calling [<code>emitter.setMaxListeners(n)</code>][] still has\nprecedence over <code>EventEmitter.defaultMaxListeners</code>.\n\n</p>\n<p>Note that this is not a hard limit. The <code>EventEmitter</code> instance will allow\nmore listeners to be added but will output a trace warning to stderr indicating\nthat a <code>possible EventEmitter memory leak</code> has been detected. For any single\n<code>EventEmitter</code>, the <code>emitter.getMaxListeners()</code> and <code>emitter.setMaxListeners()</code>\nmethods can be used to temporarily avoid this warning:\n\n</p>\n<pre><code>emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once(&#39;event&#39;, () =&gt; {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});</code></pre>\n"
            }
          ]
        }
      ]
    }
  ]
}
