Skip to content
Node.js

EventEmitter

Emit and listen for custom events.

#events#eventemitter#async

Code

nodejs
import { EventEmitter } from "events";

class JobQueue extends EventEmitter {
  constructor() {
    super();
    this.queue = [];
  }
  enqueue(job) {
    this.queue.push(job);
    this.emit("job", job);
    if (this.queue.length > 100) this.emit("warning", this.queue.length);
  }
  process() {
    while (this.queue.length) {
      const job = this.queue.shift();
      this.emit("processed", job);
    }
  }
}

const queue = new JobQueue();
queue.on("job",       j => console.log("enqueued", j.id));
queue.on("warning",   n => console.warn("queue size", n));
queue.once("processed", j => console.log("first job done", j.id));

queue.enqueue({ id: 1 });
queue.enqueue({ id: 2 });
queue.process();

// Error handlers must be registered for 'error' or the process crashes
queue.on("error", err => console.error(err));