Event-driven architecture helps your app react to things happening, like clicks or messages, making it easy to handle many actions smoothly.
Event-driven architecture in 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.
emitter.on('login', (user) => { console.log(`${user} logged in`); }); emitter.emit('login', 'Alice');
once listens only for the first time the event happens.emitter.once('start', () => { console.log('Started once'); }); emitter.emit('start'); emitter.emit('start');
emitter.on('error', (err) => { console.error('Error:', err.message); }); emitter.emit('error', new Error('Something went wrong'));
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.
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'); });
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.
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.
Practice
EventEmitter in an Express app?Solution
Step 1: Understand the role of EventEmitter
EventEmitteris used to create and listen for events, enabling asynchronous reactions in the app.Step 2: Compare with other Express features
Routing, database connections, and static file serving are handled by other parts of Express, not EventEmitter.Final Answer:
To allow the app to react to events asynchronously -> Option AQuick Check:
EventEmitter = async event handling [OK]
- Confusing EventEmitter with routing or middleware
- Thinking EventEmitter manages database connections
- Assuming EventEmitter serves static files
Solution
Step 1: Recall correct import syntax
Theeventsmodule exportsEventEmitteras a property, so you must access it before creating an instance.Step 2: Check each option's syntax
const EventEmitter = require('events').EventEmitter; const emitter = new EventEmitter(); correctly importsEventEmitterand creates a new instance. const EventEmitter = require('events'); const emitter = new EventEmitter(); misses the .EventEmitter property. Options A and C misuse the constructor call.Final Answer:
const EventEmitter = require('events').EventEmitter; const emitter = new EventEmitter(); -> Option BQuick Check:
Correct import and new instance = const EventEmitter = require('events').EventEmitter; const emitter = new EventEmitter(); [OK]
- Calling EventEmitter as a function without new
- Missing .EventEmitter when requiring events
- Using new with require() directly
const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Alice');Solution
Step 1: Understand event registration
The code registers a listener for the 'greet' event that logs a greeting with the given name.Step 2: Analyze event emission
Whenemitter.emit('greet', 'Alice')runs, it triggers the listener, printing "Hello, Alice!".Final Answer:
Hello, Alice! -> Option AQuick Check:
Emit triggers listener output = Hello, Alice! [OK]
- Expecting no output without console.log
- Confusing event name with output text
- Thinking emit returns a value
const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();
emitter.emit('start');
emitter.on('start', () => {
console.log('Started');
});Solution
Step 1: Check event listener registration timing
The listener for 'start' is added afteremitter.emit('start')is called, so it misses the event.Step 2: Verify other code parts
Import and syntax are correct;emitexists and callback syntax is valid.Final Answer:
The event listener is registered after the event is emitted -> Option DQuick Check:
Listener must be before emit to catch event [OK]
- Emitting event before listener causes no output
- Assuming emit queues events for future listeners
- Misreading import or callback syntax
Solution
Step 1: Consider modular event handling
Using separate EventEmitter instances per module keeps code organized and decoupled, improving scalability.Step 2: Evaluate other options
A single global emitter can become a bottleneck. Middleware alone doesn't handle async events well. Polling is inefficient and not event-driven.Final Answer:
Create separate EventEmitter instances for different modules and communicate via events -> Option CQuick Check:
Modular emitters = scalable event-driven design [OK]
- Using one global emitter causing tight coupling
- Ignoring event-driven benefits by polling
- Relying only on middleware for async events
Ready to prove it?
Pass the test and this pattern moves unknown
