Inject middleware into require calls before they hit the cache, file system, or native modules
This library will give you the capabilities of middleware in calls to require. It's super handy for unit testing and dependency injection, but could be used for broader application purposes as well.
This is heavily inspired by, and modeled after, Connect middleware.
--save if using in your core app,
--save-dev if using for testing
npm install [--save/--save-dev] require-middleware
// Remember this is going to hijack all require calls to follow!// That also means that you might want to load it firstvar requireMiddleware = require'require-middleware';requireMiddlewareuseif reqname === 'something'// Transparent dependency replacementreturn require'somethingelse';next;;var myModule = require'something'; // Gets resolved as if I called `require('somethingelse');
If your module isn't going to block the request for the middleware (by calling
next(err)) or resolve the dependency by returning the result, calling
next() will execute the next registered middleware.
Simply pass a return value to next and that will be thrown as an exception
if reqname === 'fs'next'Sorry dude, no fs for you.';
The middleware stack is exposed on
##Naming your middleware
requireMiddlewareuse ;// ORrequireMiddlewareuse as'someOtherMiddleware';
The stack, after registering this middleware would look like:
handle: Function myMiddleware name: 'myMiddleware'handle: Function someOtherMiddleware name: 'someOtherMiddleware'
.as() function is handy if you want to load up common middleware from another location but name it something specific that you control for later manipulation on the stack. Naming middleware will not impact its functionality in any way.