Event Interceptors for EventEmitter

2.0.0 · abandoned · verified Wed Apr 22

`events-intercept` is a Node.js library designed to introduce middleware-like interception capabilities to the standard `EventEmitter`. It allows developers to define functions that execute before an event's registered handlers, providing opportunities to modify event arguments, prevent event propagation, or trigger additional events based on intercepted data. The library extends `events.EventEmitter`, adding methods such as `intercept`, `interceptors`, `removeInterceptor`, and `removeAllInterceptors` to manage these pre-handler hooks. The current and last stable version is 2.0.0, released in 2015. This package is no longer actively maintained, making it unsuitable for new projects requiring ongoing support or modern JavaScript features like ES Modules. Its primary differentiator, historically, was providing a structured, waterfall-like approach to event processing, akin to request middleware, directly within the `EventEmitter` paradigm.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `EventEmitter` with multiple interceptors for an event, showing how data can be transformed in a pipeline. It also illustrates how an interceptor can prevent the original event's handlers from being called while emitting new events.

const EventEmitter = require('events-intercept').EventEmitter;
const emitter = new EventEmitter();

emitter
  .on('data', function(arg) {
    console.log(`Handler received: ${arg}`);
  })
  .intercept('data', function(arg, done) {
    // Interceptor 1: Modify data
    console.log(`Interceptor 1 received: ${arg}`);
    return done(null, 'intercepted_1_' + arg);
  })
  .intercept('data', function(arg, done) {
    // Interceptor 2: Further modify data
    console.log(`Interceptor 2 received: ${arg}`);
    return done(null, 'intercepted_2_' + arg);
  });

console.log('Emitting event with initial data...');
emitter.emit('data', 'initial data');
// Expected output:
// Emitting event with initial data...
// Interceptor 1 received: initial data
// Interceptor 2 received: intercepted_1_initial data
// Handler received: intercepted_2_initial data

console.log('\nEmitting another event, but intercepting to prevent original handler...');
emitter.intercept('no-callback-event', function(arg, done) {
    console.log(`Interceptor for 'no-callback-event' received: ${arg}. Not calling done().`);
    // Do not call done(), so the original 'no-callback-event' handler is never invoked.
    this.emit('alternative-event', 'transformed ' + arg);
});
emitter.on('no-callback-event', () => console.log('This should not log!'));
emitter.on('alternative-event', (arg) => console.log(`Alternative event handler received: ${arg}`));
emitter.emit('no-callback-event', 'original data');

view raw JSON →