event-emitter-map v1.0.0-r1
event-emitter-map
event-emitter-map is a small utility that enhances Node.js EventEmitter to support an object-based syntax for adding multiple event listeners in a single call.
Features
- Add listeners using an object with event names as keys.
- Works with
.on(),.once(),.off(),.prependListener(),.prependOnceListener(), and others.
Installation
npm install event-emitter-mapUsage
import { enable, disable } from 'event-emitter-map';
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
enable(); // or: enable(['on']);
emitter.on({
event1: () => console.log('event1'),
event2: () => console.log('event2')
});
emitter.emit('event1'); // Outputs: 'event1'
emitter.emit('event2'); // Outputs: 'event2'
disable(); // Restore default behaviorRationale
Spawning workers in async often comes with something like this:
// Promise.all for array of:
new Promise((message, error) =>
new Worker(new URL('./worker.mjs', import.meta.url), { workerData: { banana } })
.on('message', message)
.on('error', error)
)Which can be simplified to:
new Promise((message, error) =>
new Worker(new URL('./worker.mjs', import.meta.url), { workerData: { banana } }).on({ message, error })
)Additionally, the syntax allows for a concise notation for named non-arrow functions:
worker.on({
message() { this.terminate(); }
});Functions defined this way are not anonymous and maintain the correct context for this, while also being more concise than minimal arrow functions, which lack both named identifiers and proper context.
Enabling by Default
You can automatically enable the enhancer by importing it with a force query parameter:
import './node_modules/event-emitter-map/src/index.mjs?force';API
enable([methods])
Enhances the specified EventEmitter methods (defaults to ['on', 'once', 'off', 'addListener', 'removeListener', 'prependListener', 'prependOnceListener']).
disable([methods])
Restores the original EventEmitter methods.
License
MIT