DEV Community

Grace Valerie Anyango
Grace Valerie Anyango

Posted on

2 2

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay