
Event Emitting and Middleware Hooks
Features
- Simple replacement for EventEmitter
- Async / Sync Middleware Hooks for Your Methods
- ESM / CJS with Types
- Browser Support and Delivered via CDN
- Ability to throw errors in hooks
- Ability to pass in a logger (such as Pino) for errors
- Enforce consistent hook naming conventions with
enforceBeforeAfter
- Deprecation warnings for hooks with
deprecatedHooks
- Control deprecated hook execution with
allowDeprecated
- WaterfallHook for sequential data transformation pipelines
- ParallelHook for concurrent fan-out execution with collected results
- Tag hooks and look them up across events with
getHooksByTag and getTaggedHooks
- Optional hook stats, off by default unless you set
enableStats or stats.enabled
- No package dependencies and only 250KB in size
- Fast and Efficient with Benchmarks
- Maintained on a regular basis!
Table of Contents
- Installation
- Usage
- Migrating from v2 to v3
- Migrating from v1 to v2
- Using it in the Browser
- Hooks
- API - Hooks
- .allowDeprecated
- .deprecatedHooks
- .enforceBeforeAfter
- .eventLogger
- .hooks
- .throwOnHookError
- .stats
- .useHookClone
- .addHook(event, handler)
- .afterHook(eventName, ...args)
- .beforeHook(eventName, ...args)
- .callHook(eventName, ...args)
- .clearHooks()
- .getHook(id)
- .getHooks(eventName)
- .getHooksByTag(tag)
- .getTaggedHooks()
- .hook(eventName, ...args)
- .hookSync(eventName, ...args)
- .onHook(hook, options?)
- .onHooks(Array, options?)
- .onceHook(hook)
- .prependHook(hook, options?)
- .prependOnceHook(hook, options?)
- .removeEventHooks(eventName)
- .removeHook(hook)
- .removeHookById(id)
- .removeHooks(Array)
- API - Events
- Logging
- Hook Stats
- Benchmarks
- How to Contribute
- License and Copyright
Installation
npm install hookified --save
Usage
This was built because we constantly wanted hooks and events extended on libraires we are building such as Keyv and Cacheable. This is a simple way to add hooks and events to your classes.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
//with hooks you can pass data in and if they are subscribed via onHook they can modify the data
async myMethodWithHooks(): Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
You can even pass in multiple arguments to the hooks:
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks(): Promise<any> {
let data = { some: 'data' };
let data2 = { some: 'data2' };
// do something
await this.hook('before:myMethod2', data, data2);
return data;
}
}
Using it in the Browser
<script type="module">
import { Hookified } from 'https://cdn.jsdelivr.net/npm/hookified/dist/browser/index.js';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
//with hooks you can pass data in and if they are subscribed via onHook they can modify the data
async myMethodWithHooks(): Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
</script>
if you are not using ESM modules, you can use the following:
<script src="https://cdn.jsdelivr.net/npm/hookified/dist/browser/index.global.js"></script>
<script>
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
//with hooks you can pass data in and if they are subscribed via onHook they can modify the data
async myMethodWithHooks(): Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
</script>
Hooks
Standard Hook
The Hook class provides a convenient way to create hook entries. It implements the IHook interface.
The IHook interface has the following properties:
| Property |
Type |
Required |
Description |
id |
string |
No |
Unique identifier for the hook. Auto-generated via crypto.randomUUID() if not provided. |
event |
string |
Yes |
The event name for the hook. |
handler |
HookFn |
Yes |
The handler function for the hook. |
tags |
string[] |
No |
Tags for grouping and looking up hooks across events. |
When a hook is registered, it is assigned an id (auto-generated if not provided). The id can be used to look up or remove hooks via getHook and removeHookById. If you register a hook with the same id on the same event, it will replace the existing hook in-place (preserving its position).
Hooks can also carry tags, an optional array of strings used to group and look them up across events. When a hook is registered, tags are validated, copied, and de-duplicated while keeping the first-seen order. Matching is exact and case-sensitive: "audit", "Audit", and " audit" are three different tags. An empty string, a non-string, or a non-array throws a TypeError and the hook is not registered. Changing the array you passed in after registering has no effect, because the stored tags are a copy. Tags are not trimmed or lowercased. With useHookClone: false, the tags property on your hook object is replaced with that normalized copy, the same way id is assigned onto it.
Using the Hook class: