Home / Articles

Documenting events from EventEmitter

2020-08-08T15:11:50.638Z.

This article describes how to document events emitted from EventEmitter in a Node.js application. This article assumes you are using Visual Studio Code.

Documenting EventEmitter class

Assume we have a EchoChamber class, which inherits from the EventEmitter, provides 2 functions:

Let's also assume the EchoChamber emits 2 types of event:

We can document the events using the @typedef tag at the top of the file:


/**
 * @typedef {'whisper'|'shout'} EchoChamberEvent
 */

The EchoChamberEvent type defines the event names.

We then override and document the on() and once() functions:


/**
 * Listens on the event emiited.
 *
 * @param {EchoChamberEvent} name Event name.
 * @param {(message: string) => void} handler Event handler.
 */
on(name, handler) {
  return super.on(name, handler);
}

/**
 * Listens on the event emitted for once.
 *
 * @param {EchoChamberEvent} name Event name.
 * @param {(message: string) => void} handler Event handler.
 */
once(name, handler) {
  return super.once(name, handler);
}

IntelliSense in Visual Studio Code

With the event names documented, Visual Studio Code can give appropriate hints when we call on() and once() functions:

IntelliSense in Visual Studio Code.

We can see that we can listen on whisper and shout events. If we try to listen on an undocumented event, Visual Studio Code shows us an error message:

Error message in Visual Studio Code.

Sample codes

The complete sample codes of the EchoChamber class:


'use strict';

/**
  * @typedef {'whisper'|'shout'} EchoChamberEvent
  */

const EventEmitter = require('events');

const MAX_DELAY = 3000;

class EchoChamber extends EventEmitter {
  /**
    * Listens on the events emiited.
    *
    * @param {EchoChamberEvent} name Event name.
    * @param {(message: string) => void} handler Event handler.
    */
  on(name, handler) {
    return super.on(name, handler);
  }

  /**
    * Listens on the  events emitted for once.
    *
    * @param {EchoChamberEvent} name Event name.
    * @param {(message: string) => void} handler Event handler.
    */
  once(name, handler) {
    return super.once(name, handler);
  }

  /**
    * Whispers a message into the echo chamber.
    *
    * @param {string} message Message.
    */
  whisper(message) {
    const delay = Math.floor(Math.random() * MAX_DELAY);
    setTimeout(() => {
      this.emit('whisper', message.toLowerCase());
    }, delay);
  }

  /**
    * Shouts a message into the echo chamber.
    *
    * @param {string} message Message.
    */
  shout(message) {
    const delay = Math.floor(Math.random() * MAX_DELAY);
    setTimeout(() => {
      this.emit('shout', message.toUpperCase());
    }, delay);
  }
}

module.exports = EchoChamber;

References