Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including filter-chain with all npm packages installed. Try it out:

var filterChain = require("filter-chain")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

filter-chain v1.0.1

request chaining ala Servlets filters

ServletsFilter style request chaining.

This is very simple single file module, but provides a nice structure for webapps allowing you to introduce configurable aspects to each request.

The chain is configured in code, you can externalize it if you need.


First load a set of filters

var attributesFilter = require("../server/attributes-filter"), logRequestFilter = require("../server/log-request-filter") serverHeaderFilter = require("../server/server-header-filter"), notModifiedFilter = require("../server/not-modified-filter"), routerFilter = require("../server/router");

Create an ordered array of the filters and pass it to the FilterChain constructor

var chainModules = [ attributesFilter, logRequestFilter, serverHeaderFilter, notModifiedFilter, routerFilter ];

var chain = new FilterChain(chainModules);

Then, in a server start, the chain with it's execute() method, passing the request and response.

http.createServer(function(request, response) { // N.B a typical router should be in the chain //router.route(request, response);

chain.execute(request, response);


That's it, nothing special, but a usefull design pattern.

Filters look identical to Java Servlets filters.

var parse = require('url').parse;

filter = function(request, response, chain) {

var url = parse(request.url);
console.log(request.method + " " + url.pathname);

chain.doFilter(request, response);


exports.filter = filter;

You must export a function called "filter", but the module can do any thing else as well.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free