DEV Community

Grace Valerie Anyango
Grace Valerie Anyango

Posted on

Event emitters in node js

EventEmitter is a class of the event module that can be used to raise and handle custom events. This module facilitates communication between objects in Node and is at the core of asynchronous event-driven architecture. This class has properties like on which is used to bind functions on events and emit which fires events.

emit() function

this function is used to create an event and it takes one parameter which is the event name.

const events = require('events')

const eventEmitter = new events.EventEmitter()
eventEmitter.emit('nameOfEvent')
Enter fullscreen mode Exit fullscreen mode

on() function

This function binds an event with an event handler JavaScript function and it takes two parameters:

  • name of event to bind
  • EventHandler Function
// we require the module events
const EventEmitter = require('events')

const customEmitter = new EventEmitter()
// the event _myEvent_ is bound to the function parameter
customEmitter.on('myEvent', (name, age ) => {
   console.log(`My name is ${name} and I am ${age} years old`)
})
//myEvent is triggered
customEmitter.emit('myEvent', 'Grace', 22)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)