Node.js / Node.js Event-Driven Programming

Creating and Handling Custom Events

In this tutorial, you'll learn to create custom events using Node.js's EventEmitter class. You'll also learn to handle these events effectively.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores the event-driven architecture and the EventEmitter class in Node.js.

Creating and Handling Custom Events

1. Introduction

This tutorial aims to teach you how to create custom events using Node.js's EventEmitter class and how to handle these events effectively.

By the end of this tutorial, you'll learn:

  • How to create custom events
  • How to emit custom events
  • How to handle custom events

Prerequisites: Basic knowledge of Node.js and JavaScript is required.

2. Step-by-Step Guide

Node.js's EventEmitter class allows you to create and handle custom events. You can require it and create an instance of the EventEmitter class to use it.

Creating Custom Events

To create a custom event, you use the .on() method of the EventEmitter instance. This method takes two arguments: the name of the event (a string) and a callback function to be called when the event is emitted.

Emitting Custom Events

To emit a custom event, you use the .emit() method of the EventEmitter instance. This method takes the name of the event as its first argument and any data you want to pass to the event handler as subsequent arguments.

Handling Custom Events

The callback function you passed to the .on() method is the event handler. This function is called whenever the event is emitted, and it receives the data passed to the .emit() method as its arguments.

3. Code Examples

Example 1

// Require the EventEmitter class
const EventEmitter = require('events');

// Create an instance of the EventEmitter class
const myEmitter = new EventEmitter();

// Create a custom event
myEmitter.on('sayHello', (name) => {
  console.log(`Hello, ${name}!`);
});

// Emit the custom event
myEmitter.emit('sayHello', 'Alice');

In this example, we create a custom event named 'sayHello'. When this event is emitted, it logs a greeting to the console. We then emit the 'sayHello' event with the name 'Alice', so it logs 'Hello, Alice!'.

Example 2

const EventEmitter = require('events');
const myEmitter = new EventEmitter();

// Create a custom event with multiple arguments
myEmitter.on('sum', (a, b) => {
  console.log(`The sum of ${a} and ${b} is ${a+b}`);
});

// Emit the custom event
myEmitter.emit('sum', 5, 3);

In this example, the 'sum' event takes two arguments and logs their sum. We emit the 'sum' event with the numbers 5 and 3, so it logs 'The sum of 5 and 3 is 8'.

4. Summary

In this tutorial, we've learned:

  • How to create custom events using the .on() method of an EventEmitter instance
  • How to emit custom events using the .emit() method of an EventEmitter instance
  • How to handle custom events using callback functions

Next, you might want to learn about error handling in Node.js, or how to use streams and buffers.

5. Practice Exercises

  1. Create a custom event that logs the product of two numbers. Emit this event with the numbers 3 and 4.
  2. Create a custom event that logs a greeting. This event should take one argument: the name of the person to greet. Emit this event with your name.
  3. Create a custom event that logs a message. This event should take two arguments: a string and a number. The string is a message, and the number is the number of times to log the message. Emit this event with a message of your choice and the number 5.

Solutions

  1. Here's how you could solve the first exercise:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();

myEmitter.on('multiply', (a, b) => {
  console.log(`The product of ${a} and ${b} is ${a*b}`);
});

myEmitter.emit('multiply', 3, 4);
  1. Here's a solution for the second exercise:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();

myEmitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

myEmitter.emit('greet', 'Your name');
  1. Here's a solution for the third exercise:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();

myEmitter.on('repeat', (message, times) => {
  for (let i = 0; i < times; i++) {
    console.log(message);
  }
});

myEmitter.emit('repeat', 'This is my message.', 5);

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help