How to listen for events in Node.js

Listening for events is fundamental to Node.js event-driven architecture, enabling asynchronous communication between different parts of your application. As the creator of CoreUI with over 25 years of development experience building Node.js applications since 2014, I’ve implemented event listeners extensively in backend services for handling user actions, file operations, and inter-service communication. The most reliable approach is using the on() method on EventEmitter instances to register event listeners that respond to specific events. This method provides clean separation of concerns and enables scalable, loosely-coupled application architecture.

Use the on() method to listen for events on EventEmitter instances and execute callback functions when events are emitted.

const EventEmitter = require('events')
const emitter = new EventEmitter()

// Listen for 'userLogin' events
emitter.on('userLogin', (userData) => {
  console.log(`User ${userData.name} logged in at ${new Date()}`)
  // Handle login logic here
})

// Listen for 'error' events
emitter.on('error', (error) => {
  console.error('An error occurred:', error.message)
})

// Emit events to trigger listeners
emitter.emit('userLogin', { name: 'John', id: 123 })
emitter.emit('error', new Error('Something went wrong'))

The on() method registers an event listener that executes whenever the specified event is emitted. The first parameter is the event name (string), and the second is the callback function that receives any data passed with the event. Event listeners run asynchronously and can access event data through callback parameters. Multiple listeners can be attached to the same event, and they’ll execute in the order they were registered, making this pattern perfect for modular, event-driven applications.

Best Practice Note:

This is the event handling pattern we use in CoreUI backend services for building scalable, event-driven Node.js applications. Always handle ’error’ events to prevent uncaught exceptions, and consider using once() instead of on() for events that should only trigger one time.


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