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.
Table of Content
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 withemit, manage them withoff, and handle errors with theerrorevent.
FAQs
What are Node JS Events?
EventEmitter object handles events.
- They allow asynchronous programming.
- They are the core of real-time apps.
- They work with
emitandon.
How do you use EventEmitter in Node.js?
- Import
eventsmodule - Create an
EventEmitterobject - Register event with
on - Emit the event using
emit
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?
- Enable asynchronous operations
- Support real-time communication
- Improve scalability
- Make programs responsive
Similar Reads
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 store raw binary data in memory. This guide shows how to create them, work with them, and…
Node Package Manager (NPM) is an essential tool at the heart of the Node.js ecosystem. This is the defacto package…
In this quick tutorial, you will start Node.js tutorials with a Hello World program. You will learn how to set…
NVM (Node Version Manager ) is a command-line tool used to manage multiple versions of Node.js on a single machine.…
This guide shows Node.js modules, how they work, how to import and export them, and why you use them. What…
Streams pass data in parts, so the app stays fast. This article explains Node.js Streams and how to use them.…
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, or macOS. You need to pick the version of Node.js that you want to…
Node.js file system lets you read, write, update, and manage files and folders with built-in methods. Understand the Node.js File…