How to use events in Node.js

Working with events is fundamental to Node.js architecture, enabling asynchronous communication between different parts of your application. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development, I’ve built numerous Node.js applications where event-driven patterns are essential for scalability. The most effective approach is using Node.js’s built-in EventEmitter class, which provides a robust foundation for creating and handling custom events. This pattern allows for loose coupling between components and enables reactive programming paradigms.

Use the EventEmitter class to create custom events and handle asynchronous communication in your Node.js applications.

const EventEmitter = require('events')

const myEmitter = new EventEmitter()

myEmitter.on('data', (message) => {
  console.log('Received:', message)
})

myEmitter.emit('data', 'Hello World')

The EventEmitter class provides methods for registering event listeners with on() and triggering events with emit(). When you emit an event, all registered listeners for that event are called asynchronously. You can pass data to listeners as additional arguments to the emit() method. This pattern is the foundation of many Node.js core modules like HTTP servers, streams, and file system operations.

Best Practice Note:

This is the same event-driven architecture we use in CoreUI backend services for handling real-time updates and inter-service communication. Always remember to handle errors with error events and consider using once() for one-time listeners to prevent memory leaks.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author