How to create event emitters in Node.js

Creating custom event emitters allows you to build modular, reactive components that communicate through events rather than direct method calls. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development, I’ve designed countless Node.js services where custom event emitters provide clean separation of concerns. The most effective approach is extending the EventEmitter class to create specialized event emitters that encapsulate specific business logic. This pattern enables loose coupling and makes your code more testable and maintainable.

Extend the EventEmitter class to create custom event emitters with specialized functionality and clean APIs.

const EventEmitter = require('events')

class DataProcessor extends EventEmitter {
  process(data) {
    this.emit('start', data)

    const result = data.toUpperCase()

    this.emit('complete', result)
    return result
  }
}

const processor = new DataProcessor()
processor.on('complete', (result) => console.log('Done:', result))
processor.process('hello world')

By extending EventEmitter, your class inherits all event functionality while adding custom methods that emit relevant events. This approach allows external code to listen for specific events without tight coupling to your class implementation. The class can emit events at different stages of processing, enabling reactive programming patterns and easier testing through event mocking.

Best Practice Note:

This is the pattern we use in CoreUI backend services for creating data processors, file handlers, and API clients. Always emit an ’error’ event for error conditions and consider using descriptive event names that clearly indicate the state or action being communicated.


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