0
0
Expressframework~30 mins

Event-driven architecture in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Simple Event-Driven Server with Express
📖 Scenario: You are creating a small web server that reacts to events. This server will listen for HTTP requests and emit custom events when certain routes are accessed. This helps separate the logic of handling requests and responding to events.
🎯 Goal: Build an Express server that uses Node.js event-driven architecture. You will create an event emitter, set up a listener for a custom event, and trigger that event when a specific route is visited.
📋 What You'll Learn
Create an Express app instance
Create a Node.js EventEmitter instance
Set up an event listener for a custom event named userVisited
Emit the userVisited event when the /visit route is accessed
Send a response confirming the event was emitted
💡 Why This Matters
🌍 Real World
Event-driven architecture helps build scalable and maintainable servers by separating event handling from request processing.
💼 Career
Understanding event-driven patterns is essential for backend developers working with Node.js and Express to build responsive and modular applications.
Progress0 / 4 steps
1
Set up Express and EventEmitter
Create a constant called express that requires the 'express' module. Then create a constant called app by calling express(). Also, create a constant called EventEmitter that requires the 'events' module, and create a constant called eventEmitter by calling new EventEmitter().
Express
Need a hint?

Use require('express') to import Express and require('events') to import the EventEmitter class.

2
Create a listener for the 'userVisited' event
Use eventEmitter.on to listen for the event named 'userVisited'. The listener should be a function that takes a username parameter and logs the message `User visited: ${username}` to the console.
Express
Need a hint?

Use eventEmitter.on('userVisited', (username) => { ... }) to set up the listener.

3
Emit the 'userVisited' event on route access
Create a GET route on /visit using app.get. Inside the route handler, emit the 'userVisited' event on eventEmitter with the string 'Alice' as the username. Then send the response 'Welcome Alice!'.
Express
Need a hint?

Use app.get('/visit', (req, res) => { ... }) and inside call eventEmitter.emit('userVisited', 'Alice').

4
Start the Express server
Add app.listen to start the server on port 3000. The callback function should log 'Server running on port 3000' to the console.
Express
Need a hint?

Use app.listen(3000, () => { console.log('Server running on port 3000') }) to start the server.