Node JS Events in Depth with Examples

node js events in depth

Node JS runs code in an event-based model and uses events to drive tasks. An event is a signal that tells the program to run a task at a set time. The core module for events is called EventEmitter, and it gives a way to work with events.

Understand the EventEmitter in Node.js

EventEmitter is a built-in module that sends and receives named signals inside a Node.js app. It allows the code to fire custom actions and to react to them at once.

You create an EventEmitter object and define custom events with it, and then react to those events. You can set up a function that runs each time the event fires, and so control app flow.

The emit method sends out an event signal, and the on method listens to that signal. This model gives control over how parts of your code respond to events and data.

You can add many listeners to the same event, and you can also remove them later. The removeListener or off method stops a function from running when that event fires again.

You can link events so one fires after another and build a flow of actions.
This method is useful in tasks that need many steps and need an order between them.

You can catch errors in an EventEmitter by using a special error event.
This event lets the code react to faults and stop them from breaking the app.

Examples

Basic EventEmitter:

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

emitter.on('start', () => {
  console.log('Start event fired');
});

emitter.emit('start');

This code creates an EventEmitter object and sets a listener for a “start” event and then fires it with emit to show a basic event flow.

Event with Data:

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

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

emitter.emit('message', 'Hello Node');

This code adds a listener for “message” and passes data with emit so the listener uses that data to run extra logic at run time.

Remove a Listener:

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

function onConnect() {
  console.log('Connected');
}

emitter.on('connect', onConnect);
emitter.emit('connect');
emitter.off('connect', onConnect);
emitter.emit('connect');

This code attaches a listener, fires the event, then removes the listener, and fires the event again so nothing runs the second time.

Chain Events:

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

emitter.on('step1', () => {
  console.log('Step 1');
  emitter.emit('step2');
});

emitter.on('step2', () => {
  console.log('Step 2');
});

emitter.emit('step1');

This code links two events so “step1” fires first and then triggers “step2” to build a sequence of actions inside the app.

Wrapping Up

You learned how Node JS handles events and how EventEmitter works and how to chain and remove events and how to handle errors.

Here is a quick recap:

  • You can create an EventEmitter, add listeners with on, send events with emit, manage them with off, and handle errors with the error event.

FAQs

What are Node JS Events?

Node JS Events are signals that something has happened in the application. Node.js uses an event-driven model where an EventEmitter object handles events.
  • They allow asynchronous programming.
  • They are the core of real-time apps.
  • They work with emit and on.

How do you use EventEmitter in Node.js?

To use EventEmitter, you import it, create an instance, then define and listen to events.
  1. Import events module
  2. Create an EventEmitter object
  3. Register event with on
  4. Emit the event using emit
Example:

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

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

emitter.emit('greet');

What is the difference between on() and once() in Node.js?

- on() listens to an event every time it is emitted. - once() listens only once and then removes itself. Example:

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

emitter.on('ping', () => {
  console.log('Ping received multiple times');
});

emitter.once('pong', () => {
  console.log('Pong received only once');
});

emitter.emit('ping');
emitter.emit('ping');
emitter.emit('pong');
emitter.emit('pong');

Why are events important in Node.js?

Events make Node.js efficient by handling many tasks without blocking the program.
  • Enable asynchronous operations
  • Support real-time communication
  • Improve scalability
  • Make programs responsive

Similar Reads

Node.js REPL: The Complete Tutorial for Beginners

Node.js REPL runs JavaScript code in an instant test space inside your terminal. What is Node.js REPL? Node.js REPL is…

Node JS Buffers Tutorial for Beginners and Pros

Node JS Buffers store raw binary data in memory. This guide shows how to create them, work with them, and…

Node js NPM: How to Publish and Install JS Packages

Node Package Manager (NPM) is an essential tool at the heart of the Node.js ecosystem. This is the defacto package…

Node.js Hello World: Write Your First Program

In this quick tutorial, you will start Node.js tutorials with a Hello World program. You will learn how to set…

Node Version Manager (NVM): Manage Node.js Versions

NVM (Node Version Manager ) is a command-line tool used to manage multiple versions of Node.js on a single machine.…

Node.js Modules in Depth with Examples

This guide shows Node.js modules, how they work, how to import and export them, and why you use them. What…

Node.js Streams Guide: How to Handle Data with Examples

Streams pass data in parts, so the app stays fast. This article explains Node.js Streams and how to use them.…

Node.js HTTP Server with Examples for Beginners

This article shows how Node.js creates HTTP servers. It covers requests, responses, routes, HTML, JSON, and gives examples for both…

Installing Node js on Windows, Ubuntu, and MacOS

Installing node js on Windows, Ubuntu, or macOS. You need to pick the version of Node.js that you want to…

Node.js File System with Examples

Node.js file system lets you read, write, update, and manage files and folders with built-in methods. Understand the Node.js File…

Previous Article

What is HTML for Beginners and How it Works for Beginners

Next Article

Forms in React: How to Create and Manage User Inputs

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.