Handling Asynchronous Events in Node.js
Node.js·3 min read·Feb 12, 2025
In Node.js, the core API is built around an asynchronous event-driven architecture in which certain objects called "emitters" send named signals called "events" to other objects called "listeners" that perform specific actions in response.
The EventEmitter class
All objects that emit events are instances of the EventEmitter class defined in the node:events module:
const EventEmitter = require('node:events');When the EventEmitter object emits an event, all the functions attached to that specific event are called synchronously.
Creating an event emitter
To create an event emitter object, you can use the new keyword to instantiate the EventEmitter class:
const EventEmitter = require('node:events');const emitter = new EventEmitter();Emitting named events
To emit a named event, you can use the emit() method of the event emitter instance:
emitter.emit(name, ...arguments?);Where:
Unlock the Build CLI Apps in JavaScript & Node.js module
Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.
You get immediate access to:
- 45 focused lessons across JavaScript, Node.js, npm, and Git
- 17 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle