Patrones de dise帽o en Node.js
Qu茅 es Node.js y c贸mo impulsa tu negocio
Patrones de dise帽o esenciales en Node.js
Patr贸n Singleton y Factory en JavaScript
Implementaci贸n pr谩ctica de Singleton y Factory en JavaScript
Implementaci贸n del patr贸n Observer con EventEmitter en Node.js
Implementaci贸n de Middlewares en Node.js sin Express
Decorators e inyecci贸n de dependencias en JavaScript
Flujo de Datos con Node.js
Aprende qu茅 son Buffer y Streams en Node.js
C贸mo utilizar streams y pipelines en Node.js
C贸mo funciona el Event Loop en Node.js
Qu茅 es Libuv y c贸mo maneja la asincron铆a en Node.js
Estrategias para ejecutar c贸digo as铆ncrono en Node.js
Debugging y Diagn贸stico en Node.js
C贸mo utilizar el Debugger en Node.js para solucionar problemas
Uso de Diagnostic Channels en Node.js para observabilidad y diagn贸stico
Instrumentaci贸n y m茅tricas clave en performance para aplicaciones Node.js
Control de errores globales y manejo de se帽ales en Node.js
Implementaci贸n Eficiente de Logs con Pino en Node.js
Performance en Node.js
An谩lisis del event loop en aplicaciones Node.js usando Nsolid
C贸mo Diagnosticar y Solucionar Memory Leaks en Aplicaciones Node.js
Optimizar rendimiento en Node.js con Worker Threads y Child Processes
Optimiza y Escala Aplicaciones Node.js con T茅cnicas de Caching
Creando CLIs con Node.js
C贸mo crear aplicaciones CLI con Node.js
C贸mo Crear un CLI con Minimist y Manejar Argumentos en Node.js
Creaci贸n de un CLI con Node.js y Google Generative AI
Creaci贸n de Chat con IA usando CLI en Node
C贸mo Crear e Instalar tu Propio CLI de Node con npm
You don't have access to this class
Keep learning! Join and start boosting your career
The Observer pattern is an effective way used within the Node.js Core to develop event-driven applications, allowing you to react to specific events through a mechanism called Event Emitter. This mechanism allows you to emit events that other modules will listen for in order to execute specific code, thus facilitating a modular and clearly organized software architecture.
The Observer pattern is a design model that uses the Event Emitter in Node.js, where an object receives notifications when certain events occur and responds to execute a specific action. This pattern, also known as observer pattern, allows:
It is implemented by creating classes that extend the Node.js core Event Emitter, to benefit from these capabilities directly from the base.
To implement the Observer, we start by creating a file called Notifier
where we first import the EventEmitter module provided by Node.js:
const EventEmitter = require("node:events");class UserNotifier extends EventEmitter {}module.exports = new UserNotifier();
This basic structure provides security by explicitly using the node
prefix :
avoiding vulnerabilities in malicious packages published in external logs.
Following the Observer structure, the general flow consists ofemitters andlisteners:
We create a function called RegisterUser
that, in addition to simulating a user registration, emits the userRegister
event:
const notifier = require('./Notifier');function RegisterUser(user) { console.log('Registering user'); notifier.emit('userRegister', user); return user;}
To react to each event we need to create dedicated listener modules. Example with an EmailListener
and a StatsListener
:
const notifier = require('../Notifier');notifier.on('userRegister', (user) => { console.log(`Send email to ${user.email}`);});
const notifier = require('../Notifier');notifier.on('userRegister', (user) => { console.log(`Update stats for ${user}`);});
These listeners are automatically triggered when the event is triggered from the sender.
The main file(index.js
) executes the entire stream, importing only the listeners and the sender:
const registerUser = require('./UserRegistration');require('./Listeners/EmailListener');require('./Listeners/StatsListener');const user1 = {name: 'User1', email: '[email protected]'};const user2 = {name:'User2', email: '[email protected]'};registerUser(user1);registerUser(user2);
When this code is executed, the previously defined events are emitted, and each listener responds by executing the defined actions, such as sending emails or updating statistics, allowing to verify in console the correct execution:
Registering userSend email to [email protected]Update stats to [Object object]Registering userSend email to [email protected]Update stats to [Object object]
To reduce risks in Node.js projects when using modules native to the environment, it is recommended to explicitly indicate the module using the annotation:
require("node:module")
This measure prevents possible attacks by malicious publication of external packages in NPM.
In order to go deeper into the Observer pattern using Event Emitter, it is convenient to perform practical exercises such as:
(postCreated
).I invite you to apply these additional exercises to gain confidence and fluency in handling events with Node.js. Do you have any specific questions on how to continue?
Contributions 3
Questions 0
Want to see more contributions, questions and answers from the community?