Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6

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…


This content originally appeared on DEV Community and was authored by Abdelhakim mohamed

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! 🎉


This content originally appeared on DEV Community and was authored by Abdelhakim mohamed


Print Share Comment Cite Upload Translate Updates
APA

Abdelhakim mohamed | Sciencx (2024-09-20T09:38:30+00:00) Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6. Retrieved from https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/

MLA
" » Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6." Abdelhakim mohamed | Sciencx - Friday September 20, 2024, https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/
HARVARD
Abdelhakim mohamed | Sciencx Friday September 20, 2024 » Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6., viewed ,<https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/>
VANCOUVER
Abdelhakim mohamed | Sciencx - » Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/
CHICAGO
" » Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6." Abdelhakim mohamed | Sciencx - Accessed . https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/
IEEE
" » Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6." Abdelhakim mohamed | Sciencx [Online]. Available: https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/. [Accessed: ]
rf:citation
» Understanding Events in Node.js with Simple Code Examples – Node.js Tutorial – Part 6 | Abdelhakim mohamed | Sciencx | https://www.scien.cx/2024/09/20/understanding-events-in-node-js-with-simple-code-examples-node-js-tutorial-part-6/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.