Skip to content

The Node Event emitter

How to work with custom events in Node

If you worked with JavaScript in the browser, you know how much of the interaction of the user is handled through events: mouse clicks, keyboard button presses, reacting to mouse movements, and so on.

On the backend side, Node offers us the option to build a similar system using the events module.

This module, in particular, offers the EventEmitter class, which we’ll use to handle our events.

You initialize an EventEmitter object using this syntax:

const EventEmitter = require('events')
const eventEmitter = new EventEmitter()

This object exposes, among many others, the on and emit methods.

Emit and listen for events

For example, let’s create a start event, and as a matter of providing a sample, we react to that by just logging to the console:

eventEmitter.on('start', () => {
  console.log('started')
})

When we run

eventEmitter.emit('start')

the event handler function is triggered, and we get the console log.

addListener() is an alias for on(), in case you see that used.

Passing arguments to the event

You can pass arguments to the event handler by passing them as additional arguments to emit():

eventEmitter.on('start', (number) => {
  console.log(`started ${number}`)
})

eventEmitter.emit('start', 23)

Multiple arguments:

eventEmitter.on('start', (start, end) => {
  console.log(`started from ${start} to ${end}`)
})

eventEmitter.emit('start', 1, 100)

Listen for an event just once

The EventEmitter object also exposes the once() method, which you can use to create a one-time event listener.

Once that event is fired, the listener stops listening.

Example:

eventEmitter.once('start', () => {
  console.log(`started!`)
})

eventEmitter.emit('start')
eventEmitter.emit('start') //not going to fire

Removing an event listener

Once you create an event listener, you can remove it using the removeListener() method.

To do so, we must first have a reference to the callback function of on.

In this example:

eventEmitter.on('start', () => {
  console.log('started')
})

Extract the callback:

const callback = () => {
  console.log('started')
}

eventEmitter.on('start', callback)

So that later you can call

eventEmitter.removeListener('start', callback)

You can also remove all listeners at once on an event, using:

eventEmitter.removeAllListeners('start')

Getting the events registered

The eventNames() method, called on an EventEmitter object instance, returns an array of strings that represent the events registered on the current EventListener:

const EventEmitter = require('events')
const eventEmitter = new EventEmitter()

eventEmitter.on('start', () => {
  console.log('started')
})

eventEmitter.eventNames() // [ 'start' ]

listenerCount() returns the count of listeners of the event passed as parameter:

eventEmitter.listenerCount('start') //1

Adding more listeners before/after other ones

If you have multiple listeners, the order of them might be important.

An EventEmitter object instance offers some methods to work with order.

emitter.prependListener()

When you add a listener using on or addListener, it’s added last in the queue of listeners, and called last. Using prependListener it’s added, and called, before other listeners.

emitter.prependOnceListener()

When you add a listener using once, it’s added last in the queue of listeners, and called last. Using prependOnceListener it’s added, and called, before other listeners.


→ Get my Node.js Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about node: