Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Tag: v0.0.0
Fetching contributors…

Cannot retrieve contributors at this time

78 lines (54 sloc) 2.514 kB

remap - reroute require for mocks, wrappers, or shenanigans

open up node's module loading code and gives you control of what is happening.

basic examples

load a module, but replace specific modules with a different implementation:

var Remapper = require ('remap')
  , remapper = new Remapper(module,{
  'path/module-a':'newpath/module-b' 
//, ...
})
remapper.require('path/module-a') // will load 'newpath/module-b' instead.

remapper can also tell you the dependency tree of the module's it's loaded.

remapper.depends

will give something like:

{ module: 
  { dependency: 
    { another: {}
    , etc:{}
    }
  }
}

reloading a module multiple times

var newCache = {}
  , modules = require ('remap/modules').useCache(newCache)
  , require2 = modules.makeRequire(module) //must pass in your module.
  , x = require2('xzy')

//now x will be cached in newCache, not require.cache

advanced usage

var modules = require ('remap/modules')
  , require2 = modules.makeRequire(module) //must pass in your module.

var x = require2('path/to/module/x')

x is the same as if you loaded it with require() x can load sub modules, and will see a require function. but it will be a require function created by remap.

makeRequire has a second argument, makeRequire(module,tools) which is a map to functions to use for the main parts of require's task:

{ 
  //resolve: called before load. returns [id,path/to/module]
  resolve: function (request,_module){
    return resolve.resolveModuleFilename(request,_module)
  }//_module is module doing the requesting.

  //load: returns the new module's exports. insert mocks & wrappers here.
, load: function (id, filename, parent, makeRequire,cache) {
    return modules.defaultLoad(id,filename,parent,makeRequire)
  }

  //make: is called by default load, should return a new makeRequire 
  //that will be used by children of newModule.
, make: function (newModule){
    //returns a makeRequire function for the newly loaded module
    return modules.makeMake(newModule, tools)
  }
}

this was composed by copy/pasting from github.com/ry/node/src/node.js and spliting it into multiple modules, adding exports, refactoring, testing and adding as little as possible.

I'll be the first to admit that alot of the code in here is a bit ugly, and further development will be forth coming...

Jump to Line
Something went wrong with that request. Please try again.