Search code examples
node.jsmodulerequire

require a module from memory instead of from disk - is this possible?


I'd like to require a Node.js module from memory, e.g. because it is generated at runtime or received from a network stream.

Is this possible at all?

How could you resolve this issue (without writing to disk and loading from there, of course)?

Basically, something such as:

var code = 'module.exports = { foo: "bar" };';
var obj = require(code);
console.log(obj.foo); // => bar

The only approach I can currently think of is using the eval function, such as:

var myModule = {};
eval(
  '(function (module) {' +
  '  var local = 5;' +
  '  module.exports = {' +
  '    foo: \'bar\'' +
  '  };' +
  '  module.exports.baz = \'baz\';' +
  '})(myModule)');

After evaluating, myModule.exports contains the exported object:

{
  foo: 'bar',
  baz: 'baz'
}

and anything that should be local inside the module stays local.

Hence, you could create a function require2, such as:

var require2 = function (code) {
  var temp = {};
  eval('(function (module) {' + code + '})(temp);');
  return temp.exports;
};

Anyway, I am interested in better ideas ... :-)

PS: Being able to require from a stream would be awesome :-)


Solution

  • In the absence of a better idea I now went with the approach I had already described in my question with a few tweaks, but the general idea is to do:

    var require2 = function (code) {
      var temp = {};
      eval('(function (module) {' + code + '})(temp);');
      return temp.exports;
    };