DEV Community

flavio ⚡️🔥
flavio ⚡️🔥

Posted on • Originally published at flaviocopes.com on

The Node Event emitter

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 that using

const eventEmitter = require('events').EventEmitter()
Enter fullscreen mode Exit fullscreen mode

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

  • emit is used to trigger an event
  • on is used to add a callback function that's going to be executed when the event is triggered

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')
})
Enter fullscreen mode Exit fullscreen mode

When we run

eventEmitter.emit('start')
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

Multiple arguments:

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

eventEmitter.emit('start', 1, 100)
Enter fullscreen mode Exit fullscreen mode

The EventEmitter object also exposes several other methods to interact with events, like

  • once(): add a one-time listener
  • removeListener() / off(): remove an event listener from an event
  • removeAllListeners(): remove all listeners for an event

You can read all their details on the events module page at https://nodejs.org/api/events.html

Top comments (0)