CodePark/ questions / EventEmitter
START PRACTICINGPRACTICE
Backend question · Node.js › EventEmitter

What is EventEmitter, and what are its main methods?

EventEmitter from node:events is a class that lets objects send named events to listeners. It implements the observer pattern: listeners subscribe to an event, and the emitter calls them when the event happens. Much of Node's core is built on it. Streams, HTTP servers, sockets and process are all emitters.

The main methods:

  • on(name, listener) registers a listener. Its alias is addListener.
  • once registers a listener that is removed after the first call.
  • emit(name, ...args) calls all listeners for that event.
  • off (alias removeListener) removes one listener. removeAllListeners removes all of them.
  • prependListener adds a listener to the front of the list.
  • listenerCount returns how many listeners are attached.

emit calls the listeners synchronously, in the order they were registered. It returns true if there were any listeners.

The error event is special. If you emit error and no listener is attached, Node throws the error.

  • EventEmitter implements the observer pattern and is the base of streams, servers and process.
  • The main methods are on, once, emit, off and removeAllListeners.
  • Listeners run synchronously, in registration order.
  • Emitting an error event with no listener throws.