Patrones de dise帽o en Node.js

1

Qu茅 es Node.js y c贸mo impulsa tu negocio

2

Patrones de dise帽o esenciales en Node.js

3

Patr贸n Singleton y Factory en JavaScript

4

Implementaci贸n pr谩ctica de Singleton y Factory en JavaScript

5

Implementaci贸n del patr贸n Observer con EventEmitter en Node.js

6

Implementaci贸n de Middlewares en Node.js sin Express

7

Decorators e inyecci贸n de dependencias en JavaScript

Flujo de Datos con Node.js

8

Aprende qu茅 son Buffer y Streams en Node.js

9

C贸mo utilizar streams y pipelines en Node.js

10

C贸mo funciona el Event Loop en Node.js

11

Qu茅 es Libuv y c贸mo maneja la asincron铆a en Node.js

12

Estrategias para ejecutar c贸digo as铆ncrono en Node.js

Debugging y Diagn贸stico en Node.js

13

C贸mo utilizar el Debugger en Node.js para solucionar problemas

14

Uso de Diagnostic Channels en Node.js para observabilidad y diagn贸stico

15

Instrumentaci贸n y m茅tricas clave en performance para aplicaciones Node.js

16

Control de errores globales y manejo de se帽ales en Node.js

17

Implementaci贸n Eficiente de Logs con Pino en Node.js

Performance en Node.js

18

An谩lisis del event loop en aplicaciones Node.js usando Nsolid

19

C贸mo Diagnosticar y Solucionar Memory Leaks en Aplicaciones Node.js

20

Optimizar rendimiento en Node.js con Worker Threads y Child Processes

21

Optimiza y Escala Aplicaciones Node.js con T茅cnicas de Caching

Creando CLIs con Node.js

22

C贸mo crear aplicaciones CLI con Node.js

23

C贸mo Crear un CLI con Minimist y Manejar Argumentos en Node.js

24

Creaci贸n de un CLI con Node.js y Google Generative AI

25

Creaci贸n de Chat con IA usando CLI en Node

26

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

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
7 Hrs
13 Min
52 Seg

Implementaci贸n del patr贸n Observer con EventEmitter en Node.js

5/26
Resources

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.

what is the Observer pattern and how does Node.js use it?

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:

  • Emit events(emit).
  • Listen to events(on).

It is implemented by creating classes that extend the Node.js core Event Emitter, to benefit from these capabilities directly from the base.

how to build a user registration Notifier with Event Emitter?

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.

what are the steps to execute events and responses?

Following the Observer structure, the general flow consists ofemitters andlisteners:

we emit a registered user event

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;}

we listen for specific events

To react to each event we need to create dedicated listener modules. Example with an EmailListener and a StatsListener:

  • EmailListener.js
const notifier  = require('../Notifier');notifier.on('userRegister', (user)  =>  {    console.log(`Send email to ${user.email}`);});
  • StatsListener.js
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.

how is it implemented and used in the main or index file?

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]

what are the security recommendations and best practices?

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.

What practical exercises can you do to master EventEmitter?

In order to go deeper into the Observer pattern using Event Emitter, it is convenient to perform practical exercises such as:

  • Simulating another type of event, such as the creation of a post by a user(postCreated).
  • Implement different listeners, such as statistics related to posts or specific notifications when a post is published in a blog channel or similar.
  • Issue events with different information objects to practice and strengthen their correct management within the event-driven architecture.

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

Sort by:

Want to see more contributions, questions and answers from the community?

```js const { postNotifier } = require('./notifier'); function newPost(user, post) { const postWithAuthor = { ...post, author: user.name }; console.log('Creating post...', postWithAuthor); postNotifier.emit('postCreated', postWithAuthor); } module.exports = newPost; ``` ```js const EventEmitter = require('node:events'); class UserNotifier extends EventEmitter {} class CreatePostNotifier extends EventEmitter {} const notifier = new UserNotifier(); const postNotifier = new CreatePostNotifier(); module.exports = { notifier, postNotifier }; ```const notifier = require('../notifier'); function postCreated(post) {聽 聽 console.log(`Post ${post.title} created with content ${post.content}`);} notifier.postNotifier.on('postCreated', postCreated); module.exports = postCreated;```js const { notifier, postNotifier } = require('../notifier'); function logStats(user) { console.log('Logging stats...', user); } function logNewPost(post) { console.log('New post created...', post); } notifier.on('userRegistered', logStats); postNotifier.on('postCreated', logNewPost); module.exports = { logStats, logNewPost }; ``````js const notifier = require('../notifier'); function postCreated(post) { console.log(`Post ${post.title} created with content ${post.content}`); } notifier.postNotifier.on('postCreated', postCreated); module. Exports = postCreated; ```module. Exports ```js const emailListener = require('./listeners/emailListeners'); const statsListener = require('./listeners/statsListener'); const postCreated = require('./listeners/newPostListener'); const registeredUser = require('./userRegistration'); const newPost = require('./userPost'); const user1 = { id: 1, name: 'John Doe', email: '[email protected]', }; const user2 = { id: 2, name: 'Jane Doe', email: '[email protected]', }; const newPost1 = { id: 1, title: 'My first post', content: 'This is the content of my first post', }; const newPost2 = { id: 2, title: 'My second post', content: 'This is the content of my second post', }; registeredUser(user1); registeredUser(user2); newPost(user1, newPost1); newPost(user2, newPost2); ```
Con el patr贸n Observer puedes crear cosas bastante interesantes. En la clase no se aprecia todo el potencial de este porque se usa desde la consola (que es muy v谩lido), y no se observa completamente su utilidad, pero en esencia est谩 muy bien. Pero si quieres entender el real potencial de este patr贸n, te recomiendo (a ti, alumno) ejecutar estos eventos con acciones reales, es decir, crea una app "m谩s real", como por ejemplo: simular pagos, env铆o de correos reales, procesamiento de datos en segundo plano. Y te aseguro que lo entender谩s mejor por el simple hecho de que te toca manejar asincronismo. No es nada aprender observabilidad, si no observar y manejar el asincronismo. Int茅ntalo y ver谩s. Saludos.
El patr贸n Observer permite desacoplar la l贸gica de negocios de la l贸gica de presentaci贸n y notificaci贸n. Al emitir eventos, los componentes que est谩n interesados en esos eventos pueden reaccionar sin que el c贸digo que los emite necesite conocer sus implementaciones. En el ejemplo, si se ejecuta el env铆o de email directamente en la funci贸n de creaci贸n del usuario, se introduce dependencia, haciendo m谩s dif铆cil realizar cambios. Con el patr贸n Observer, los listeners pueden ser a帽adidos o modificados sin afectar la funci贸n principal, lo que mejora la mantenibilidad del c贸digo y promueve la reutilizaci贸n.