Understanding Events in Node.js with Simple Code Examples - Tutorial - Part 6
Abdelhakim mohamed
Posted on September 20, 2024
What are Events?
In Node.js, an event is an action that can be listened to and acted upon. Imagine events as a notification system. Whenever something happens, like a file read completion or a request received, Node.js triggers an event that you can respond to.
EventEmitter
Node.js has a built-in module called events
, and the most important class in this module is EventEmitter
. It allows you to define and handle events.
Example 1: Basic Event Emitter
Let’s see how to create an event emitter.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// Register an event listener
myEmitter.on('greet', () => {
console.log('Hello there!');
});
// Emit the event
myEmitter.emit('greet');
In this example, we registered a listener for the greet
event and then emitted the event. The result is a simple "Hello there!" printed to the console.
Example 2: Passing Arguments with Events
You can also pass arguments when emitting events. This is helpful when you need to pass data.
myEmitter.on('sayHello', (name) => {
console.log(`Hello, ${name}!`);
});
myEmitter.emit('sayHello', 'Alice');
Now, when we emit the sayHello
event, it greets Alice.
Example 3: Using Events in a Simple HTTP Server
Let’s create a basic HTTP server and demonstrate how events come into play. In Node.js, the http
module uses events extensively. Every time a request hits the server, it triggers an event.
const http = require('http');
// Create a server
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.write('Hello World');
res.end();
}
});
// Register an event listener for 'request'
server.on('request', (req, res) => {
console.log(`Received request for ${req.url}`);
});
// Start the server
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example:
- A basic HTTP server is created.
- An event listener is added for the
'request'
event to log each request URL. - Whenever the server gets a request, the
request
event is emitted, which is picked up by the listener, logging the requested URL.
Example 4: Custom Events in a Server
You can create custom events within your server code to handle specific tasks. Here's an example of emitting a custom event when a client connects.
const EventEmitter = require('events');
const http = require('http');
// Create an event emitter instance
const myEmitter = new EventEmitter();
// Create a server
const server = http.createServer((req, res) => {
res.write('Hello Client');
res.end();
// Emit a custom event on each request
myEmitter.emit('clientConnected', req.url);
});
// Listen for the custom 'clientConnected' event
myEmitter.on('clientConnected', (url) => {
console.log(`A client connected to ${url}`);
});
// Start the server
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example:
- We create a custom event,
clientConnected
, that fires whenever a client makes a request to the server. - The listener for this event logs the URL of the request when the event is emitted.
Why Use Events?
- Non-blocking I/O: Node.js is all about handling asynchronous tasks efficiently. Events allow you to respond when tasks are completed without blocking the execution.
- Modular code: Events help you decouple your code, making it more modular and easier to manage.
Final Thoughts
Events are at the heart of Node.js, making it powerful for handling asynchronous operations, especially in the context of servers. By mastering events, you’ll have a strong foundation for building scalable and efficient applications.
Thank you for reading, and happy coding! 🎉
Posted on September 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 20, 2024