An event in NodeJS is an action or occurrence, such as a user click, a file being read, or a message being received, that NodeJS can respond to. Events are managed using the EventEmitter class, which is part of NodeJS's built-in events module. This allows NodeJS to react to various actions asynchronously.
How Do Events Work in NodeJS?
1. Event-Driven Model
- NodeJS uses an event-driven approach, meaning it waits for events (such as a user action or data) to occur and then takes action when those events happen.
2. EventEmitter
- An
EventEmitter
is an object that can generate events in NodeJS. - You can set up "listeners" that wait for these events to happen and then run a function (called a callback) when the event occurs.
3. Event Loop
- The event loop is a mechanism that runs in the background, continuously checking for events.
- When an event occurs, the event loop triggers the callback function that was registered for that event.
EventEmitter Class
At the core of the NodeJS event system is the EventEmitter class. This class allows objects to emit named events that can be listened to by other parts of your application. It is included in the built-in events module.
Key Features of EventEmitter
- on(event, listener): Adds a listener that waits for a specific event to occur.
- emit(event, [arg1, arg2, ...]): Triggers an event and calls all the listeners associated with it.
- once(event, listener): Adds a listener that is executed only the first time the event is triggered.
- removeListener(event, listener): Removes a specific listener for an event.
- removeAllListeners(event): Removes all listeners for a particular event.
Working with Events in NodeJS
Step 1: Importing the Events Module
To use events in your application, first import the events module and create an instance of the EventEmitter class.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Step 2: Registering Event Listeners
You can register listeners for specific events using the on() method. The first argument is the event name, and the second is the callback function that gets executed when the event is emitted.
myEmitter.on('event', () => {
console.log('An event occurred!');
});
Step 3: Emitting Events
To trigger an event, use the emit() method with the event name as the first argument. It will call all the listeners attached to that event.
myEmitter.emit('event'); // Output: An event occurred!
Listening events
Before emitting an event, you must first register listeners (callback functions) that will listen for the event.
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.once(event, listener)
Removing Listener
To remove a listener for an event, use removeListener() method with the event name and listener function. If you want to remove all listeners for an event, use removeAllListeners().
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
Note:
- Removing the listener from the array will change the sequence of the listener's array, hence it must be carefully used.
- The eventEmitter.removeListener() will remove at most one instance of the listener which is in front of the queue.
Now, let us understand with the help of the example:
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};
var fun2 = (msg) => {
console.log("Message from fun2: " + msg);
};
// Registering fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
// Removing listener fun1 that was
// registered on the line 13
eventEmitter.removeListener('myEvent', fun1);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
// Removing all the listeners to myEvent
eventEmitter.removeAllListeners('myEvent');
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
Output:
Message from fun1: Event occurred
Message from fun2: Event occurred
eventEmitter.listeners()
It returns an array of listeners for the specified event.
Syntax:
eventEmitter.listeners(event)
eventEmitter.listenerCount()
It returns the number of listeners listening to the specified event.
Syntax:
eventEmitter.listenerCount(event)
eventEmitter.prependOnceListener()
It will add the one-time listener to the beginning of the array.
Syntax:
eventEmitter.prependOnceListener(event, listener)
eventEmitter.prependListener()
It will add the listener to the beginning of the array.
Syntax:
eventEmitter.prependListener(event, listener)
Now, let us understand with the help of the example:
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Declaring listener fun1 to myEvent1
var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};
// Declaring listener fun2 to myEvent2
var fun2 = (msg) => {
console.log("Message from fun2: " + msg);
};
// Listening to myEvent with fun1 and fun2
eventEmitter.addListener('myEvent', fun1);
// fun2 will be inserted in front of listeners array
eventEmitter.prependListener('myEvent', fun2);
// Listing listeners
console.log(eventEmitter.listeners('myEvent'));
// Count the listeners registered to myEvent
console.log(eventEmitter.listenerCount('myEvent'));
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
Output:
[ [Function: fun2], [Function: fun1] ]
2
Message from fun2: Event occurred
Message from fun1: Event occurred
Special Events
All EventEmitter instances emit the event 'newListener' when new listeners are added and 'removeListener' existing listeners are removed.
- Event: 'newListener' This event is emitted when a new listener is added. It's triggered before the listener is added to the internal array.
eventEmitter.once( 'newListener', listener)
eventEmitter.on( 'newListener', listener)
- Event: 'removeListener' The 'removeListener' event is emitted after a listener is removed.
eventEmitter.once( ‘removeListener’, listener)
eventEmitter.on( 'removeListener’, listener)
- Event: 'error' When an error occurs, the 'error' event is emitted. If no listener is attached to this event, Node.js will throw an error and terminate the process.
eventEmitter.on('error', listener)
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Register to error
eventEmitter.on('error', (err) => {
console.error('whoops! there was an error');
});
// Register to newListener
eventEmitter.on( 'newListener', (event, listener) => {
console.log(`The listener is added to ${event}`);
});
// Register to removeListener
eventEmitter.on( 'removeListener', (event, listener) => {
console.log(`The listener is removed from ${event}`);
});
// Declaring listener fun1 to myEvent1
var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};
// Declaring listener fun2 to myEvent2
var fun2 = (msg) => {
console.log("Message from fun2: " + msg);
};
// Listening to myEvent with fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
// Removing listener
eventEmitter.off('myEvent', fun1);
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
// Triggering error
eventEmitter.emit('error', new Error('whoops!'));
Output:
The listener is added to removeListener
The listener is added to myEvent
The listener is added to myEvent
The listener is removed from myEvent
Message from fun2: Event occurred
whoops! there was an error
Asynchronous events
The EventEmitter calls all listeners synchronously in order to which they were registered. However, we can perform asynchronous calls by using setImmediate() or process.nextTick().
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Async function listening to myEvent
eventEmitter.on('myEvent', (msg) => {
setImmediate( () => {
console.log("Message from async: " + msg);
});
});
// Declaring listener fun to myEvent
var fun = (msg) => {
console.log("Message from fun: " + msg);
};
// Listening to myEvent with fun
eventEmitter.on('myEvent', fun);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
Output:
Message from fun: Event occurred
Message from async: Event occurred
Why Are Events Important in NodeJS?
- Asynchronous Nature: Events allow NodeJS to handle multiple tasks simultaneously without blocking the main thread.
- Scalability: They help manage numerous connections or operations at the same time, improving application performance.
- Flexibility: Custom events can be defined and handled based on specific requirements.
When Should You Use Events?
- Trigger Actions: Use events when specific actions need to occur in response to events like user actions, data streams, or network requests.
- Modular Code: Events help decouple different parts of your application, making the code cleaner and more maintainable.
Conclusion
Node.js events, along with the EventEmitter
class, enable powerful asynchronous handling in applications. You can create custom events, register listeners, emit events, and even manage listener lifecycle efficiently. Understanding these methods will help you build scalable and event-driven applications.
Similar Reads
Node.js Tutorial Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
Introduction & Installation
NodeJS IntroductionNodeJS is a runtime environment for executing JavaScript outside the browser, built on the V8 JavaScript engine. It enables server-side development, supports asynchronous, event-driven programming, and efficiently handles scalable network applications. NodejsNodeJS is single-threaded, utilizing an e
4 min read
Node.js Roadmap: A Complete GuideNode.js has become one of the most popular technologies for building modern web applications. It allows developers to use JavaScript on the server side, making it easy to create fast, scalable, and efficient applications. Whether you want to build APIs, real-time applications, or full-stack web apps
6 min read
How to Install Node.js on LinuxInstalling Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions.PrerequisitesA Linux System: such a
6 min read
How to Install Node.js on WindowsInstalling Node.js on Windows is a straightforward process, but it's Important to follow the right steps to ensure smooth setup and proper functioning of Node Package Manager (NPM), which is Important for managing dependencies and packages. This guide will walk you through the official site, NVM, Wi
5 min read
How to Install NodeJS on MacOSNode.js is a popular JavaScript runtime used for building server-side applications. Itâs cross-platform and works seamlessly on macOS, Windows, and Linux systems. In this article, we'll guide you through the process of installing Node.js on your macOS system.What is Node.jsNode.js is an open-source,
6 min read
Node.js vs Browser - Top Differences That Every Developer Should KnowNode.js and Web browsers are two different but interrelated technologies in web development. JavaScript is executed in both the environment, node.js, and browser but for different use cases. Since JavaScript is the common Programming language in both, it is a huge advantage for developers to code bo
6 min read
NodeJS REPL (READ, EVAL, PRINT, LOOP)NodeJS REPL (Read-Eval-Print Loop) is an interactive shell that allows you to execute JavaScript code line-by-line and see immediate results. This tool is extremely useful for quick testing, debugging, and learning, providing a sandbox where you can experiment with JavaScript code in a NodeJS enviro
4 min read
Explain V8 engine in Node.jsThe V8 engine is one of the core components of Node.js, and understanding its role and how it works can significantly improve your understanding of how Node.js executes JavaScript code. In this article, we will discuss the V8 engineâs importance and its working in the context of Node.js.What is a V8
7 min read
Node.js Web Application ArchitectureNode.js is a JavaScript-based platform mainly used to create I/O-intensive web applications such as chat apps, multimedia streaming sites, etc. It is built on Google Chromeâs V8 JavaScript engine. Web ApplicationsA web application is software that runs on a server and is rendered by a client browser
3 min read
NodeJS Event LoopThe event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently without blocking the execution of other operations. It:Executes JavaScript synchronously first and then processes asynchronous operations.Delegates heavy tasks like I/O operations, timers, and network r
5 min read
Node.js Modules , Buffer & Streams
NodeJS ModulesIn NodeJS, modules play an important role in organizing, structuring, and reusing code efficiently. A module is a self-contained block of code that can be exported and imported into different parts of an application. This modular approach helps developers manage large projects, making them more scal
5 min read
What are Buffers in Node.js ?Buffers are an essential concept in Node.js, especially when working with binary data streams such as files, network protocols, or image processing. Unlike JavaScript, which is typically used to handle text-based data, Node.js provides buffers to manage raw binary data. This article delves into what
4 min read
Node.js StreamsNode.js streams are a key part of handling I/O operations efficiently. They provide a way to read or write data continuously, allowing for efficient data processing, manipulation, and transfer.\Node.js StreamsThe stream module in Node.js provides an abstraction for working with streaming data. Strea
4 min read
Node.js Asynchronous Programming
Node.js NPM
Node.js Deployments & Communication
Node DebuggingDebugging is an essential part of software development that helps developers identify and fix errors. This ensures that the application runs smoothly without causing errors. NodeJS is a JavaScript runtime environment that provides various debugging tools for troubleshooting the application.They help
2 min read
How to Perform Testing in Node.js ?Testing is a method to check whether the functionality of an application is the same as expected or not. It helps to ensure that the output is the same as the required output. How Testing can be done in Node.js? There are various methods by which tasting can be done in Node.js, but one of the simple
2 min read
Unit Testing of Node.js ApplicationNode.js is a widely used javascript library based on Chrome's V8 JavaScript engine for developing server-side applications in web development. Unit Testing is a software testing method where individual units/components are tested in isolation. A unit can be described as the smallest testable part of
5 min read
NODE_ENV Variables and How to Use Them ?Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicate
2 min read
Difference Between Development and Production in Node.jsIn this article, we will explore the key differences between development and production environments in Node.js. Understanding these differences is crucial for deploying and managing Node.js applications effectively. IntroductionNode.js applications can behave differently depending on whether they a
3 min read
Best Security Practices in Node.jsThe security of an application is extremely important when we build a highly scalable and big project. So in this article, we are going to discuss some of the best practices that we need to follow in Node.js projects so that there are no security issues at a later point of time. In this article, we
4 min read
Deploying Node.js ApplicationsDeploying a NodeJS application can be a smooth process with the right tools and strategies. This article will guide you through the basics of deploying NodeJS applications.To show how to deploy a NodeJS app, we are first going to create a sample application for a better understanding of the process.
5 min read
How to Build a Microservices Architecture with NodeJSMicroservices architecture allows us to break down complex applications into smaller, independently deployable services. Node.js, with its non-blocking I/O and event-driven nature, is an excellent choice for building microservices. How to Build a Microservices Architecture with NodeJS?Microservices
3 min read
Node.js with WebAssemblyWebAssembly, often abbreviated as Wasm, is a cutting-edge technology that offers a high-performance assembly-like language capable of being compiled from various programming languages such as C/C++, Rust, and AssemblyScript. This technology is widely supported by major browsers including Chrome, Fir
3 min read
Resources & Tools
Node.js Web ServerA NodeJS web server is a server built using NodeJS to handle HTTP requests and responses. Unlike traditional web servers like Apache or Nginx, which are primarily designed to give static content, NodeJS web servers can handle both static and dynamic content while supporting real-time communication.
6 min read
Node Exercises, Practice Questions and SolutionsNode Exercise: Explore interactive quizzes, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your Node proficiency at your own pace. Start coding now! #content-iframe { width: 100%; height: 500px;} @media (max-width: 768px)
4 min read
Node.js ProjectsNode.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
9 min read
NodeJS Interview Questions and AnswersNodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read