Node.js - event emitter guide

Published on
Table of Contents

Node.js has a built in class called EventEmitter, which is exported from the events module

This is an example of setting up an event listener, listening for events of error type, and console.logging when that happens:


import { EventEmitter } from 'node:events';

const myEmitter = new EventEmitter();

myEmitter.on('error', (error) => {
  console.error(error)
});

myEmitter.on('something-custom', (msg) => {
  console.log('Oh wow something happened', msg)
});

function doSomething() {
    if(Math.random() < 0.5) {
        myEmitter.emit('something-custom', 'pass some value')
    }
    else {
        myEmitter.emit('error', new Error('whoops!'));
    }
}

Using once()

If you want to set up an event listener, but only care about it the first time emitted then you can use the .once() function...

const myEmitter = new EventEmitter()
myEmitter.once('greet', () => {
    console.log("Hi! This is your first time here!");
})

myEmitter.emit('greet') // greets you
myEmitter.emit('greet') // won't do anything here