Events
Event Emitter package (@nestjs/event-emitter
) provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other.
EventEmitterModule
internally uses the eventemitter2 package.
Getting started
First install the required package:
$ npm i --save @nestjs/event-emitter
Once the installation is complete, import the EventEmitterModule
into the root AppModule
and run the forRoot()
static method as shown below:
@@filename(app.module)
import { Module } from '@nestjs/common';
import { EventEmitterModule } from '@nestjs/event-emitter';
@Module({
imports: [
EventEmitterModule.forRoot()
],
})
export class AppModule {}
The .forRoot()
call initializes the event emitter and registers any declarative event listeners that exist within your app. Registration occurs when the onApplicationBootstrap
lifecycle hook occurs, ensuring that all modules have loaded and declared any scheduled jobs.
To configure the underlying EventEmitter
instance, pass the configuration object to the .forRoot()
method, as follows:
EventEmitterModule.forRoot({
// set this to `true` to use wildcards
wildcard: false,
// the delimiter used to segment namespaces
delimiter: '.',
// set this to `true` if you want to emit the newListener event
newListener: false,
// set this to `true` if you want to emit the removeListener event
removeListener: false,
// the maximum amount of listeners that can be assigned to an event
maxListeners: 10,
// show event name in memory leak message when more than maximum amount of listeners is assigned
verboseMemoryLeak: false,
// disable throwing uncaughtException if an error event is emitted and it has no listeners
ignoreErrors: false,
});