Node.js
EventEmitter
Emit and listen for custom events.
By EZ4Code Team
eventseventemitterasync
Code
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));Explanation
EventEmitter is Node's pub/sub primitive, used internally by streams, HTTP servers, and many libraries. on registers a listener, once fires only for the first event, and emit synchronously invokes all listeners. Unhandled 'error' events throw and crash the process, so always attach an error listener.
More Node.js Snippets
fs Module
Read, write, and watch files with promises and callbacks.
HTTP Server
Build an HTTP server with the http module and routing.
Streams
Pipe, transform, and consume streams efficiently.
path Module
Join, resolve, and parse file paths cross-platform.
Buffers
Work with binary data using Buffer and TypedArrays.
Child Process
Spawn, exec, and fork external processes.