{ "source": "doc/api/events.md", "modules": [ { "textRaw": "Events", "name": "Events", "stability": 2, "stabilityText": "Stable", "type": "module", "desc": "

Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called "emitters")\nperiodically emit named events that cause Function objects ("listeners") to be\ncalled.

\n

For instance: a net.Server object emits an event each time a peer\nconnects to it; a fs.ReadStream emits an event when the file is opened;\na stream emits an event whenever data is available to be read.

\n

All objects that emit events are instances of the EventEmitter class. These\nobjects expose an eventEmitter.on() 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

When the EventEmitter object emits an event, all of the Functions attached\nto that specific event are called synchronously. Any values returned by the\ncalled listeners are ignored and will be discarded.

\n

The following example shows a simple EventEmitter instance with a single\nlistener. The eventEmitter.on() method is used to register listeners, while\nthe eventEmitter.emit() method is used to trigger the event.

\n
const EventEmitter = require('events');\nconst util = require('util');\n\nfunction MyEmitter() {\n  EventEmitter.call(this);\n}\nutil.inherits(MyEmitter, EventEmitter);\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n  console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
\n

Any object can become an EventEmitter through inheritance. The example above\nuses the traditional Node.js style prototypical inheritance using\nthe util.inherits() method. It is, however, possible to use ES6 classes as\nwell:

\n
const EventEmitter = require('events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n  console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
\n", "modules": [ { "textRaw": "Passing arguments and `this` to listeners", "name": "passing_arguments_and_`this`_to_listeners", "desc": "

The eventEmitter.emit() 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 EventEmitter, the standard this\nkeyword is intentionally set to reference the EventEmitter to which the\nlistener is attached.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', 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('event', 'a', 'b');\n
\n

It is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this keyword will no longer reference the EventEmitter instance:

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  console.log(a, b, this);\n    // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');\n
\n", "type": "module", "displayName": "Passing arguments and `this` to listeners" }, { "textRaw": "Asynchronous vs. Synchronous", "name": "asynchronous_vs._synchronous", "desc": "

The EventListener 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 setImmediate() or process.nextTick() methods:

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  setImmediate(() => {\n    console.log('this happens asynchronously');\n  });\n});\nmyEmitter.emit('event', 'a', 'b');\n
\n", "type": "module", "displayName": "Asynchronous vs. Synchronous" }, { "textRaw": "Handling events only once", "name": "handling_events_only_once", "desc": "

When a listener is registered using the eventEmitter.on() method, that\nlistener will be invoked every time the named event is emitted.

\n
const myEmitter = new MyEmitter();\nvar m = 0;\nmyEmitter.on('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n  // Prints: 1\nmyEmitter.emit('event');\n  // Prints: 2\n
\n

Using the eventEmitter.once() method, it is possible to register a listener\nthat is unregistered before it is called.

\n
const myEmitter = new MyEmitter();\nvar m = 0;\nmyEmitter.once('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n  // Prints: 1\nmyEmitter.emit('event');\n  // Ignored\n
\n", "type": "module", "displayName": "Handling events only once" }, { "textRaw": "Error events", "name": "error_events", "desc": "

When an error occurs within an EventEmitter instance, the typical action is\nfor an 'error' event to be emitted. These are treated as a special case\nwithin Node.js.

\n

If an EventEmitter does not have at least one listener registered for the\n'error' event, and an 'error' event is emitted, the error is thrown, a\nstack trace is printed, and the Node.js process exits.

\n
const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n  // Throws and crashes Node.js\n
\n

To guard against crashing the Node.js process, developers can either register\na listener for the process.on('uncaughtException') event or use the\ndomain module (Note, however, that the domain module has been\ndeprecated).

\n
const myEmitter = new MyEmitter();\n\nprocess.on('uncaughtException', (err) => {\n  console.log('whoops! there was an error');\n});\n\nmyEmitter.emit('error', new Error('whoops!'));\n  // Prints: whoops! there was an error\n
\n

As a best practice, developers should always register listeners for the\n'error' event:

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n  console.log('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n  // Prints: whoops! there was an error\n
\n", "type": "module", "displayName": "Error events" } ], "classes": [ { "textRaw": "Class: EventEmitter", "type": "class", "name": "EventEmitter", "meta": { "added": [ "v0.1.26" ] }, "desc": "

The EventEmitter class is defined and exposed by the events module:

\n
const EventEmitter = require('events');\n
\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when a listener is removed.

\n", "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "meta": { "added": [ "v0.1.26" ] }, "params": [], "desc": "

The EventEmitter instance will emit it's own 'newListener' event before\na listener is added to it's internal array of listeners.

\n

Listeners registered for the 'newListener' event will be passed the event\nname and a reference to the listener being added.

\n

The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any additional listeners registered to the same\nname within the 'newListener' callback will be inserted before the\nlistener that is in the process of being added.

\n
const myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n  if (event === 'event') {\n    // Insert a new listener in front\n    myEmitter.on('event', () => {\n      console.log('B');\n    });\n  }\n});\nmyEmitter.on('event', () => {\n  console.log('A');\n});\nmyEmitter.emit('event');\n  // Prints:\n  //   B\n  //   A\n
\n" }, { "textRaw": "Event: 'removeListener'", "type": "event", "name": "removeListener", "meta": { "added": [ "v0.9.3" ] }, "params": [], "desc": "

The 'removeListener' event is emitted after a listener is removed.

\n" } ], "methods": [ { "textRaw": "EventEmitter.listenerCount(emitter, eventName)", "type": "method", "name": "listenerCount", "meta": { "added": [ "v0.9.12" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.", "desc": "

A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n  // Prints: 2\n
\n", "signatures": [ { "params": [ { "name": "emitter" }, { "name": "eventName" } ] } ] }, { "textRaw": "emitter.addListener(eventName, listener)", "type": "method", "name": "addListener", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Alias for emitter.on(eventName, listener).

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.emit(eventName[, arg1][, arg2][, ...])", "type": "method", "name": "emit", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.

\n

Returns true if the event had listeners, false otherwise.

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "arg1", "optional": true }, { "name": "arg2", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "emitter.getMaxListeners()", "type": "method", "name": "getMaxListeners", "meta": { "added": [ "v1.0.0" ] }, "desc": "

Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nEventEmitter.defaultMaxListeners.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "emitter.listenerCount(eventName)", "type": "method", "name": "listenerCount", "meta": { "added": [ "v3.2.0" ] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {Value} The name of the event being listened for ", "name": "eventName", "type": "Value", "desc": "The name of the event being listened for" } ] }, { "params": [ { "name": "eventName" } ] } ], "desc": "

Returns the number of listeners listening to the event named eventName.

\n" }, { "textRaw": "emitter.listeners(eventName)", "type": "method", "name": "listeners", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Returns a copy of the array of listeners for the event named eventName.

\n
server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n  // Prints: [ [Function] ]\n
\n", "signatures": [ { "params": [ { "name": "eventName" } ] } ] }, { "textRaw": "emitter.on(eventName, listener)", "type": "method", "name": "on", "meta": { "added": [ "v0.1.101" ] }, "desc": "

Adds the listener function to the end of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.

\n
server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\n
\n

Returns a reference to the EventEmitter so calls can be chained.

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.once(eventName, listener)", "type": "method", "name": "once", "meta": { "added": [ "v0.3.0" ] }, "desc": "

Adds a one time listener function for the event named eventName. The\nnext time eventName is triggered, this listener is removed and then invoked.

\n
server.once('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
\n

Returns a reference to the EventEmitter so calls can be chained.

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeAllListeners([eventName])", "type": "method", "name": "removeAllListeners", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Removes all listeners, or those of the specified eventName.

\n

Note that it is bad practice to remove listeners added elsewhere in the code,\nparticularly when the EventEmitter instance was created by some other\ncomponent or module (e.g. sockets or file streams).

\n

Returns a reference to the EventEmitter so calls can be chained.

\n", "signatures": [ { "params": [ { "name": "eventName", "optional": true } ] } ] }, { "textRaw": "emitter.removeListener(eventName, listener)", "type": "method", "name": "removeListener", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Removes the specified listener from the listener array for the event named\neventName.

\n
var callback = (stream) => {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
\n

removeListener 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 eventName, then removeListener must be\ncalled multiple times to remove each instance.

\n

Note that once an event has been emitted, all listeners attached to it at the\ntime of emitting will be called in order. This implies that any removeListener()\nor removeAllListeners() calls after emitting and before the last listener\nfinishes execution will not remove them from emit() in progress. Subsequent\nevents will behave as expected.

\n
const myEmitter = new MyEmitter();\n\nvar callbackA = () => {\n  console.log('A');\n  myEmitter.removeListener('event', callbackB);\n};\n\nvar callbackB = () => {\n  console.log('B');\n};\n\nmyEmitter.on('event', callbackA);\n\nmyEmitter.on('event', callbackB);\n\n// callbackA removes listener callbackB but it will still be called.\n// Internal listener array at time of emit [callbackA, callbackB]\nmyEmitter.emit('event');\n  // Prints:\n  //   A\n  //   B\n\n// callbackB is now removed.\n// Internal listener array [callbackA]\nmyEmitter.emit('event');\n  // Prints:\n  //   A\n
\n

Because listeners are managed using an internal array, calling this will\nchange the position indices of any listener registered after 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 emitter.listeners() method will need to be recreated.

\n

Returns a reference to the EventEmitter so calls can be chained.

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.setMaxListeners(n)", "type": "method", "name": "setMaxListeners", "meta": { "added": [ "v0.3.5" ] }, "desc": "

By default EventEmitters will print a warning if more than 10 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 emitter.setMaxListeners() method allows the limit to be modified for this\nspecific EventEmitter instance. The value can be set to Infinity (or 0)\nto indicate an unlimited number of listeners.

\n

Returns a reference to the EventEmitter so calls can be chained.

\n", "signatures": [ { "params": [ { "name": "n" } ] } ] } ], "properties": [ { "textRaw": "EventEmitter.defaultMaxListeners", "name": "defaultMaxListeners", "meta": { "added": [ "v0.11.2" ] }, "desc": "

By default, a maximum of 10 listeners can be registered for any single\nevent. This limit can be changed for individual EventEmitter instances\nusing the emitter.setMaxListeners(n) method. To change the default\nfor all EventEmitter instances, the EventEmitter.defaultMaxListeners\nproperty can be used.

\n

Take caution when setting the EventEmitter.defaultMaxListeners because the\nchange effects all EventEmitter instances, including those created before\nthe change is made. However, calling emitter.setMaxListeners(n) still has\nprecedence over EventEmitter.defaultMaxListeners.

\n

Note that this is not a hard limit. The EventEmitter instance will allow\nmore listeners to be added but will output a trace warning to stderr indicating\nthat a possible EventEmitter memory leak has been detected. For any single\nEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()\nmethods can be used to temporarily avoid this warning:

\n
emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
\n" } ] } ] } ] }