What are events in NodeJs?

What Are Events?

“In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by eventssuch as user actions (mouse clicks, key presses), sensor outputs, or message passing from other programs or threads” -Wikipedia.

In simpler terms, events are actions that are performed with the use of computers and computer resources. An event is fired when you shut down your PC, open a browser, click the like button of a webpage, connect to a printer, etc.

NodeJs Events

NodeJs applications also fire events. For example:

  1. HTTP requests and responses are events.
  2. Reading a file and closing a file are also events.
  3. Connecting to a database is an event.
  4. Listening to a certain port of your environment is also an event.

I believe you now have an idea of what events are.

Creating an Event in NodeJs

const EventEmitter = require("events");

const myEventEmitter = new EventEmitter();

In the code above, we required the events module that allows us to create an event emittermyEventEmitter from the constructor function EventEmitter().

Note: An event emitter emits or fires up an event.

Registering and Firing an event

Now, let’s register an event. We can do this by using .on or addListener. Registering an event takes two arguments: the event’s name and the function to be called when the event is fired.

Then, we use the emit() method to fire the events. You can see this in action below:

const EventEmitter = require("events");
const myEventEmitter = new EventEmitter();
myEventEmitter.on("open", ()=>{
console.log("Event open emitted!");
})
myEventEmitter.addListener("close", ()=>{
console.log("Event close emitted!");
})
myEventEmitter.emit("open");
myEventEmitter.emit("close");

Order of events

You can call the same event, but with different functions, to be executed. Note that all the event functions must be performed at one call. Therefore, the following will fire twice and call the event functions twice:

const { EventEmitter } = require('events')
const eventEmitter = new EventEmitter()
eventEmitter.on('my-event', () => {console.log('my-event fired with first function')})
eventEmitter.on("my-event", ()=>{console.log('my-event fired with second function')})
// HERE WE FIRE THE EVENTS
eventEmitter.emit('my-event')
eventEmitter.emit('my-event')

Removing an event with once or removeListener

We make an event only fire once with the once method or use the removeListener to remove the listener.
A function will only be called the first time an event is fired – the second emit() method won’t be called. This is shown in the code below.

Using once()

const { EventEmitter } = require('events')
const eventEmitter = new EventEmitter()
eventEmitter.once('my-event', () => { console.log('my-event fired') })
eventEmitter.emit('my-event')
eventEmitter.emit('my-event') // The event here will not be fired!

Using removeListener()

const EventEmitter = require("events");
const myEventEmitter = new EventEmitter();
const func1 = ()=>{console.log("Function 1 called!")};
const func2 = ()=>{console.log("Function 2 called!")}
myEventEmitter.on("connect", func1);
myEventEmitter.on("connect", func2);
myEventEmitter.emit("connect");
myEventEmitter.removeListener("connect", func1);
myEventEmitter.emit("connect");

Removing all Listeners with removeAllListeners()

This takes no argument. It is used to remove all events that are registered to an event emitter.

const EventEmitter = require("events");
const myEventEmitter = new EventEmitter();
myEventEmitter.on("load", ()=>{
console.log("Web page loaded!")
})
myEventEmitter.on("close", ()=>{
console.log("Web page closed!")
})
myEventEmitter.emit("load");
myEventEmitter.removeAllListeners();
myEventEmitter.emit("close"); //This will not fire or run!

Conclusion

We have seen how to create an event emitter, register an event, and fire up an event using the events built-in module of NodeJs. We also learnt how to fire an event once with the once() or removeListener() method. Lastly, we were able to remove all events attached to an emitter using removeAllListeners().

Free Resources