Events in Node.js

·

1 min read

I heard multiple times that javascript is event-based but never really thought about how it works.

According to Wikipedia event-driven programming "is a programming paradigm in which the flow of the program is determined by events"

This doesn't say much but once I saw a simple example and that brought a lot of clarity. Will help a lot to understand it and know its internals.

Node.js has a module that you can use to create fire and listen for your own events. The essence is that we will listen for specific events and register listeners for each event. Listeners are just functions. Then we can emit events and the registered listeners will be executed. Each event is identified by a string or symbol.

By default the most basic code will look like this:

const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("testEvent", () => {
  console.log("test event");
})
emitter.emit("testEvent");

What was so good about it was the "on" method. I have seen it in https/http and in ethersjs provider.on and jquery, it's almost everywhere and much of the Node.js core API is built around it.