How to create an event in Node.js?
Tags: node
Published: 2020-12-07 00:00:00

---
  title: How to create an event in Node.js?
  published: true
  tags: Nodejs
  date: Mon Dec 07 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/create-events-in-nodejs
  cover_image: https://melvingeorge.me/_next/static/images/main-4a403281c054a21da47b420ce455c838.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/create-events-in-nodejs)
  
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**

```js
// 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 &rarr;](#full-code)

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

```js
// 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,

```js
// 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,

```js
// 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,

```js
// 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,

```js
// 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.

<a name="full-code"></a>

```js
// 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**

```bash
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](https://repl.it/@melvin2016/create-and-listen-to-events-nodejs).

**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,**

```js
// 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 😃.

---