0
0
Node.jsframework~5 mins

EventEmitter class in Node.js

Choose your learning style9 modes available
Introduction

The EventEmitter class helps your program talk to itself by sending and listening for messages called events.

You want to run some code when a file finishes loading.
You want to react when a user clicks a button in a server-side app.
You want to handle errors or special signals in your program.
You want different parts of your program to communicate without being tightly connected.
Syntax
Node.js
const EventEmitter = require('events');

const emitter = new EventEmitter();

emitter.on('eventName', (args) => {
  // code to run when eventName happens
});

emitter.emit('eventName', args);

on listens for an event.

emit triggers the event and runs all listeners.

Examples
This example listens for a 'greet' event and prints 'Hello!' when it happens.
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('greet', () => {
  console.log('Hello!');
});

emitter.emit('greet');
This example sends a message with the 'data' event and prints it when received.
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('data', (message) => {
  console.log('Received:', message);
});

emitter.emit('data', 'Node.js is fun!');
This example listens for an 'error' event and prints the error message.
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('error', (err) => {
  console.error('Error happened:', err.message);
});

emitter.emit('error', new Error('Oops!'));
Sample Program

This program creates a Door class that can emit an 'open' event. When the door opens, it prints messages before and after the event.

Node.js
const EventEmitter = require('events');

class Door extends EventEmitter {
  open() {
    console.log('Door is opening...');
    this.emit('open');
  }
}

const door = new Door();

door.on('open', () => {
  console.log('The door was opened!');
});

door.open();
OutputSuccess
Important Notes

You can add many listeners to the same event.

Listeners run in the order they were added.

If no listener is set for an 'error' event, Node.js will crash.

Summary

The EventEmitter class lets parts of your program send and listen for events.

Use on to listen and emit to send events.

This helps keep your code organized and responsive.