Thanks to visit codestin.com
Credit goes to coreui.io

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

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
Mastering JavaScript List Comprehension: The Ultimate Guide
Mastering JavaScript List Comprehension: The Ultimate Guide

How to get the last element in an array in JavaScript
How to get the last element in an array in JavaScript

How to force a React component to re-render
How to force a React component to re-render

How to Center a Button in CSS
How to Center a Button in CSS

Answers by CoreUI Core Team