0
0
Expressframework~5 mins

Event-driven architecture in Express

Choose your learning style9 modes available
Introduction

Event-driven architecture helps your app react to things happening, like clicks or messages, making it easy to handle many actions smoothly.

When you want your server to respond to user actions like form submissions or button clicks.
When your app needs to handle multiple tasks at the same time without waiting.
When you want to build real-time features like chat or notifications.
When you want to keep your code organized by separating actions into events and handlers.
Syntax
Express
const EventEmitter = require('events');
const emitter = new EventEmitter();

// Listen for an event
emitter.on('eventName', (data) => {
  console.log('Event received:', data);
});

// Trigger the event
emitter.emit('eventName', 'Hello World');

EventEmitter is a built-in Node.js class used in Express apps to handle events.

on listens for an event, and emit triggers it.

Examples
This listens for a 'login' event and prints who logged in.
Express
emitter.on('login', (user) => {
  console.log(`${user} logged in`);
});
emitter.emit('login', 'Alice');
once listens only for the first time the event happens.
Express
emitter.once('start', () => {
  console.log('Started once');
});
emitter.emit('start');
emitter.emit('start');
Handle errors by listening to an 'error' event.
Express
emitter.on('error', (err) => {
  console.error('Error:', err.message);
});
emitter.emit('error', new Error('Something went wrong'));
Sample Program

This Express app listens for a user registration event. When you visit /register/yourname, it registers the user and triggers an event that simulates sending a welcome email.

Express
const express = require('express');
const EventEmitter = require('events');

const app = express();
const eventEmitter = new EventEmitter();

// Event listener for user registration
eventEmitter.on('userRegistered', (username) => {
  console.log(`Welcome email sent to ${username}`);
});

app.get('/register/:username', (req, res) => {
  const username = req.params.username;
  // Simulate user registration logic
  res.send(`User ${username} registered successfully.`);

  // Emit event after registration
  eventEmitter.emit('userRegistered', username);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Events help keep your code clean by separating what happens from when it happens.

Use once if you want to listen to an event only one time.

Always handle 'error' events to avoid crashes.

Summary

Event-driven architecture lets your app react to actions smoothly.

Use EventEmitter in Express to create and listen for events.

This helps organize code and build real-time features easily.