How to create an event in Node.js?

Published December 7, 2020

Events in Node.js are commonly used to notify that a task or something has reached a specific point in its lifecycle. Simply put, events are used to notify the completion of a specific task.

For example, requesting an API can be an event, and receiving the response from that API can be an event.

You can create custom events in Node.js.

To create an event, you can use the default class from the events module in Node.js.

There are 3 simple things with events in Node.js:

  • The first one is creating an event
  • Second, is to declare an event has happened or trigger an event using the event emit() method (This is also called emitting an event in Node.js)
  • The third is to listen for that event
// require events module
const Event = require("events");

// create a new event
const event = new Event();

// Listening for an event
event.on("anEventName", () => {
  console.log("The event is done!");
});

// Emitting an Event
event.emit("anEventName");

Let's take a simple example of logging out numbers to the console from 1 to 100 then triggering an event when it's done.

Jump to the full code →

For that First, Let's require the default Event class from the events module like this,

// require default Event class
// from events module
const Event = require("events");

After that, we need to create a new event, Let's name it logEvent which is a better name I could think of for our example (Lazy me 😌).

It can be done like this,

// require default Event class
// from events module
const Event = require("events");

// make a new event
// called logEvent
const logEvent = new Event();

Now let's create our simple function which logs out numbers from 1 to 100 using a for loop like this,

// require default Event class
// from events module
const Event = require("events");

// make a new event
// called logEvent
const logEvent = new Event();

// function which logs
// numbers from 1 to 100 to console
function logFrom1to100() {
  for (i = 0; i < 100; i++) {
    console.log(`Number ${i + 1}`);
  }
}

After logging out numbers to the console, let's trigger or emit an event using the emit() method on the logEvent.

The emit() method takes an event name of string type as the first argument.

Let's call our event name as logged to console

it can be done like this,

// require default Event class
// from events module
const Event = require("events");

// make a new event
// called logEvent
const logEvent = new Event();

// function which logs
// numbers from 1 to 100 to console
function logFrom1to100() {
  for (i = 0; i < 100; i++) {
    console.log(`Number ${i + 1}`);
  }

  // trigger an event
  // called logged to console
  logEvent.emit("logged to console");
}

After that, we need to listen for the event logged to console outside the function.

We can use the on() method on the logEvent.

The on() method takes 2 arguments,

  • the name of the event to listen for (In our case logged to console) as the first argument
  • a callback function to execute when the event has happened

We can listen for the logged to console event like this,

// require default Event class
// from events module
const Event = require("events");

// make a new event
// called logEvent
const logEvent = new Event();

// function which logs
// numbers from 1 to 100 to console
function logFrom1to100() {
  for (i = 0; i < 100; i++) {
    console.log(`Number ${i + 1}`);
  }

  // trigger an event
  // called logged to console
  logEvent.emit("logged to console");
}

// listen for the
// logged to console
// event using the on()
// method on the logEvent
logEvent.on("logged to console", () => {
  console.log("We have successfully logged to console. Yay! 🍻");
});

Lastly, let's invoke our function logFrom1to100 to see the functioning of the event.

// require default Event class
// from events module
const Event = require("events");

// make a new event
// called logEvent
const logEvent = new Event();

// function which logs
// numbers from 1 to 100 to console
function logFrom1to100() {
  for (i = 0; i < 100; i++) {
    console.log(`Number ${i + 1}`);
  }

  // trigger an event
  // called logged to console
  logEvent.emit("logged to console");
}

// listen for the
// logged to console
// event using the on()
// method on the logEvent
logEvent.on("logged to console", () => {
  console.log("We have successfully logged to console. Yay! 🍻");
});

// invoke function logFrom1to100()
logFrom1to100();

Output

Number 1
Number 2
Number 3
.
.
.
.
.
Number 98
Number 99
Number 100
We have successfully logged to the console. Yay! 🍻

We have successfully made an event and listened to it.

See this example live in repl.it.

If you want to pass extra data when you trigger an event, you can pass that as the second argument in the emit() function and get that data as the first parameter in the on() method's callback function,

// function which logs
// numbers from 1 to 100 to console
function logFrom1to100() {
  for (i = 0; i < 100; i++) {
    console.log(`Number ${i + 1}`);
  }

  // trigger an event
  // called logged to console
  // also pass extra data as second argument
  logEvent.emit("logged to console", {
    startNumber: 1,
    endNumber: 100,
  });
}
// listen for the
// logged to console
// event using the on()
// method on the logEvent
// also get the data in the callback function
logEvent.on("logged to console", (data) => {
  console.log("We have successfully logged to console. Yay! 🍻");
  console.log(data);
});

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter