title: Changing how nodejs require() fetches files
body: <p>I'm looking to monkey-patch require() to replace its file loading with my own function.  I imagine that internally require(module_id) does something like:</p>
  
  <ol>
  <li>Convert module_id into a file path</li>
  <li>Load the file path as a string</li>
  <li>Compile the string into a module object and set up the various globals correctly</li>
  </ol>
  
  <p>I'm looking to replace step 2 without reimplementing steps 1 + 3.   Looking at the public API, there's require() which does 1 - 3, and require.resolve() which does 1.  Is there a way to isolate step 2 from step 3?   </p>
  
  <p>I've looked at the source of require mocking tools such as <a href="https://github.com/mfncooper/mockery#readme" rel="nofollow">mockery</a> -- all they seem to be doing is replacing require() with a function that intercepts certain calls and returns a user-supplied object, and passes on other calls to the native require() function.</p>
  
  <p>For context, I'm trying to write a function require_at_commit(module_id, git_commit_id), which loads a module and any of that module's requires as they were at the given commit.  </p>
  
  <p>I want this function because I want to be able to write certain functions that a) rely on various parts of my codebase, and b) are guaranteed to not change as I evolve my codebase.  I want to "freeze" my code at various points in time, so thought this might be an easy way of avoiding having to package 20 copies of my codebase (an alternative would be to have "my_code_v1": "git://..." in my package.json, but I feel like that would be bloated and slow with 20 versions). </p>
  
  <p><strong>Update:</strong></p>
  
  <p>So the source code for module loading is here: <a href="https://github.com/joyent/node/blob/master/lib/module.js" rel="nofollow">https://github.com/joyent/node/blob/master/lib/module.js</a>.  Specifically, to do something like this you would need to reimplement Module._load, which is pretty straightforward.  However, there's a bigger obstacle, which is that step 1, converting module_id into a file path, is actually harder than I thought, because resolveFilename needs to be able to call fs.exists() to know where to terminate its search... so I can't just substitute out individual files, I have to substitute entire directories, which means that it's probably easier just to export the entire git revision to a directory and point require() at that directory, as opposed to overriding require().</p>
  
  <p><strong>Update 2:</strong></p>
  
  <p>Ended up using a different approach altogether... see answer I added below</p>