Concept Flow - Event-driven architecture
Event Occurs
Event Emitted
Event Listeners Check
Listener 1
Listener 1 Action
Continue Program
When an event happens, it is emitted. Listeners waiting for that event react by running their actions.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('greet', () => { console.log('Hello!'); }); emitter.emit('greet');
| Step | Action | Event | Listeners Present | Listener Action | Output |
|---|---|---|---|---|---|
| 1 | Create EventEmitter instance | N/A | None yet | None | No output |
| 2 | Add listener for 'greet' | 'greet' | 1 listener added | Listener waits | No output |
| 3 | Emit 'greet' event | 'greet' | 1 listener active | Run listener callback | Prints 'Hello!' |
| 4 | No more events | N/A | Listeners remain | No action | Execution ends |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| emitter | undefined | EventEmitter instance | Same instance with listener | Same instance | Same instance |
| listeners for 'greet' | 0 | 0 | 1 listener function | 1 listener function | 1 listener function |
Event-driven architecture in Express: - Create an EventEmitter instance - Add listeners with .on(event, callback) - Emit events with .emit(event) - All listeners for that event run on emit - Allows decoupled, asynchronous reactions to events
EventEmitter in an Express app?EventEmitter is used to create and listen for events, enabling asynchronous reactions in the app.events module exports EventEmitter as a property, so you must access it before creating an instance.EventEmitter and creates a new instance. const EventEmitter = require('events'); const emitter = new EventEmitter(); misses the .EventEmitter property. Options A and C misuse the constructor call.const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Alice');emitter.emit('greet', 'Alice') runs, it triggers the listener, printing "Hello, Alice!".const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();
emitter.emit('start');
emitter.on('start', () => {
console.log('Started');
});emitter.emit('start') is called, so it misses the event.emit exists and callback syntax is valid.Pass the test and this pattern moves unknown