Search code examples
stringnode.jsfilerequire

Load node.js module from string in memory


How would I require() a file if I had the file's contents as a string in memory, without writing it out to disk? Here's an example:

// Load the file as a string
var strFileContents = fs.readFileSync( "./myUnalteredModule.js", 'utf8' );

// Do some stuff to the files contents
strFileContents[532] = '6';

// Load it as a node module (how would I do this?)
var loadedModule = require( doMagic(strFileContents) );

Solution

  • function requireFromString(src, filename) {
      var Module = module.constructor;
      var m = new Module();
      m._compile(src, filename);
      return m.exports;
    }
    
    console.log(requireFromString('module.exports = { test: 1}', ''));
    

    look at _compile, _extensions and _load in module.js