Lädt...

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


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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

...

🔧 Python Program Examples – Simple Code Examples for Beginners


📈 29.59 Punkte
🔧 Programmierung

🔧 Understanding Domain Events in TypeScript: Making Events Work for You


📈 26.04 Punkte
🔧 Programmierung

🔧 Understanding C# Delegates and Events with Real-World Examples


📈 26.03 Punkte
🔧 Programmierung

🎥 How To Use META AI (Complete Tutorial) Beginner Tutorial (LLAMA 3 Tutorial)


📈 25.35 Punkte
🎥 Video | Youtube

🔧 Understanding Redux: A tutorial with examples


📈 24.68 Punkte
🔧 Programmierung

🔧 5 Things I Wish I Knew Before Learning to Code (With Simple Code Examples)


📈 23.19 Punkte
🔧 Programmierung

🔧 How to Handle Events in React – Explained with Code Examples


📈 22.98 Punkte
🔧 Programmierung

🔧 10 Extension Methods examples in Dart: A Comprehensive Guide with Code Examples


📈 22.97 Punkte
🔧 Programmierung

🔧 🧠 Understanding useState, useEffect, and useRef in React (with Simple Examples)


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding Pydantic Model Validation with Simple Examples


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding REST API and RESTful: A Simple Guide with Everyday Examples


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding Flows in Android: A Simple Guide with Examples


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding HTTP Methods with Simple Examples 🔻


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding Algorithm Complexity Through 7 Simple Examples of Choosing a Book to Read


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding call, apply, and bind in JavaScript with Simple Examples


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding Java String Length: Simple Examples


📈 22.85 Punkte
🔧 Programmierung

🔧 Understanding File-Level Restore (FLR): Simple Explanation by Examples | Backup Tips


📈 22.85 Punkte
🔧 Programmierung

🔧 C++ Tutorial: Solve Real-World Problems with Code Examples


📈 21.62 Punkte
🔧 Programmierung

🔧 Step-by-Step Email Verification JavaScript Tutorial: Best Practices & Code Examples


📈 21.62 Punkte
🔧 Programmierung

🔧 SVG Tutorial – How to Code Images with 7 Examples


📈 21.62 Punkte
🔧 Programmierung

🎥 JavaScript Security Vulnerabilities Tutorial – With Code Examples


📈 21.62 Punkte
🎥 Video | Youtube

🔧 Simple Python Code Examples to Build Your Skills


📈 19.8 Punkte
🔧 Programmierung

🔧 Major Differences Between TypeScript and JavaScript: 5 Key Points with Simple Code Examples


📈 19.8 Punkte
🔧 Programmierung

🔧 Firebase Authentication Made Simple: Detailed Code Examples


📈 19.8 Punkte
🔧 Programmierung

🔧 Firebase Authentication Made Simple: Detailed Code Examples


📈 19.8 Punkte
🔧 Programmierung

🔧 Reflection In C#: 4 Simple But Powerful Code Examples


📈 19.8 Punkte
🔧 Programmierung

🔧 Understanding Singly and Doubly Linked Lists with Real-Life Examples and JavaScript Code


📈 19.61 Punkte
🔧 Programmierung

🕵️ dotCMS 3.7.0 /news-events/events date cross site scripting


📈 19.61 Punkte
🕵️ Sicherheitslücken

🕵️ Low CVE-2013-7477: Wp-events-plugin Events manager


📈 19.61 Punkte
🕵️ Sicherheitslücken

🕵️ Low CVE-2013-7478: Wp-events-plugin Events manager


📈 19.61 Punkte
🕵️ Sicherheitslücken

🕵️ Low CVE-2013-7479: Wp-events-plugin Events manager


📈 19.61 Punkte
🕵️ Sicherheitslücken