Code Monkey home page Code Monkey logo

events-intercept's Introduction

#events-intercept

Build Status Coverage Status

The node EventEmitter is very powerful. However, at times it could be valuable to intercept events before they reach their handlers, to modify the data, or emit other events. That's a job for event-intercept.

##Installation

npm install events-intercept

##Standalone Usage

The module contains a constructor, EventEmitter, which inherits from the standard node events.EventEmitter.

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

In our application, we have an object that will emit a data event, and pass it a single argument.

emitter.emit('data', 'myData')

It is very easy to listen for this event and handle it

emitter.on('data', function(arg) {
	console.log(arg);
}); //logs 'myData'

However, we want to intercept that event and modify the data. We can do that by setting an interceptor with intercept(event, interceptor). It is passed all arguments that would be passed to the emitter, as well as a standard node callback. In this case, let's just add a prefix on to the data.

emitter.intercept('data', function(arg, done) {
	return done(null, 'intercepted ' + arg);
});

This code will be executed before the handler, and the new argument will be passed on to the handler appropriately.

emitter.emit('data', 'some other data');
//logs 'intercepted some other data'

If multiple interceptors are added to a single event, they will be called in the order that they are added, like async.waterfall.

Here's that sample code all together. Of course, intercept supports proper function chaining.

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

emitter
.on('data', function(arg) {
	console.log(arg);
}).intercept('data', function(arg, done) {
	return done(null, 'intercepted ' + arg);
}).emit('data', 'myData');
//logs 'intercepted myData'

Please see test/intercept.js for more complete samples.

##Calling Separate Events

There may be times when you want to intercept one event and call another. Luckily, all intercept handlers are called with the EventEmitter as the this context, so you can emit events yourself.

emitter.intercept('data', function(done) {
	this
	.emit('otherData')
	.emit('thirdData');
	return done(null);
});
//emits 'data', 'otherData', and 'thirdData'

Remember, emitting an event that you are intercepting will cause a loop, so be careful.

In fact, an interceptor do not need to call the callback at all, which means that the event that was intercepted will never be called at all.

emitter.intercept('data', function(done) {
	this
	.emit('otherData')
	.emit('thirdData');
});
//emits 'otherData' and 'thirdData' but not 'data'

##Utilities

events-intercept supports all of the useful utilities that the standard EventEmitter supports:

  • interceptors(type) returns an array of all interceptors (functions) for the given type.
  • removeInterceptor(type, interceptor) removes an interceptor of a given type. You must pass in the interceptor function.
  • removeAllInterceptors(type) removes all interceptors for a given type.
  • removeAllInterceptors() removes all interceptors. Will remove the removeInterceptor event last, so they will all get triggered.
  • the EventEmitter will throw a warning if more than 10 interceptors are added to a single event, as this could represent a memory leak. setMaxInterceptors(n) allows you to change that. Set it to 0 for no limit.

All of these are demonstrated in the tests.

##Patching

Of course, many EventEmitters that you have the pleasure of using will not have the foresight to use event-intercept. Thankfully, Javascript is awesome, it's possible to monkey patch the interception capabilities onto an existing object. Just call

var events = require('events');
var eventsIntercept = require('events-intercept');

var emitter = new events.EventEmitter();

eventsIntercept.patch(emitter)

emitter
.on('data', function(arg) {
	console.log(arg);
}).intercept('data', function(arg, done) {
	return done(null, 'intercepted ' + arg);
}).emit('data', 'myData');
//logs 'intercepted myData'

Now, you should be able to call intercept on the standard EventEmitter.

This is also shown in test/intercept.js.

events-intercept's People

Contributors

brandonhorst avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

events-intercept's Issues

Patching `http.ClientRequest` breaks ensuing `http.IncomingMessage`s

If I make an http request using http.request() and patch the returned http.ClientRequest object, the http.IncomingMessage that I get from it doesn't fire data events. This occurs in node 0.10.26 but NOT v0.8.8, so it's probably due to some optimization that occurred between those versions. Here's an example:

var eventsIntercept = require('events-intercept');
var http = require('http');

function handleResponse (response, type) {
  console.log(type + ": got response object!");
  var buf = "";
  response.on('data', function (chunk, asdf) {
    buf += chunk;
    console.log(type + ": data event!");
  });

  response.on('end', function () {
    console.log(type + ": response done! buf: " + buf.slice(0, 30));
  });
}

var clientRequestPatched = http.request("http://www.google.com");
eventsIntercept.patch(clientRequestPatched);
clientRequestPatched.on('response', function (response) {
  handleResponse(response, "patched");
});
clientRequestPatched.end();

var clientRequestUnpatched = http.request("http://www.google.com");
clientRequestUnpatched.on('response', function (response) {
  handleResponse(response, "unpatched");
});
clientRequestUnpatched.end();

var clientRequest = http.request("http://www.google.com");
var origEmit = clientRequest.emit;
clientRequest.emit = function () {
  origEmit.apply(clientRequest, arguments);
};
clientRequest.on('response', function (response) {
  handleResponse(response, "modified emit");
});
clientRequest.end();

If I run this using node v0.10.26, I get this output:

$ node0.10 manual_test.js
modified emit: got response object!
modified emit: response done! buf:
unpatched: got response object!
unpatched: data event!
unpatched: data event!
unpatched: data event!
unpatched: data event!
unpatched: data event!
unpatched: data event!
unpatched: data event!
unpatched: data event!
unpatched: response done! buf: <!doctype html><html itemscope
patched: got response object!
patched: response done! buf:

The unpatched request properly produces data events and a filled buffer when it's done. If I patch it using events-intercept, or, in fact, modify its emit function in any way, it breaks the ensuing http.IncomingMessage and no data events are fired.

If I run this using node v0.8.8:

$ node manual_test.js
patched: got response object!
patched: data event!
modified emit: got response object!
modified emit: data event!
unpatched: got response object!
unpatched: data event!
patched: data event!
patched: data event!
patched: data event!
patched: data event!
patched: data event!
patched: data event!
unpatched: data event!
unpatched: data event!
unpatched: data event!
modified emit: data event!
unpatched: data event!
unpatched: data event!
modified emit: data event!
modified emit: data event!
patched: data event!
patched: data event!
patched: data event!
patched: response done! buf: <!doctype html><html itemscope
modified emit: data event!
unpatched: data event!
unpatched: data event!
modified emit: data event!
modified emit: data event!
modified emit: response done! buf: <!doctype html><html itemscope
unpatched: data event!
unpatched: response done! buf: <!doctype html><html itemscope

All three requests get data events and a filled buffer.

For my purposes I've found that patching the http.ClientRequest by replacing its .on .addListener and .once methods works.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.