alphadogg alphadogg - 3 months ago 16
Node.js Question

Require() from string into object

Assuming I have the content of a js file in a string. Furthermore, assume it has an

exports['default'] = function() {...}
and/or other exported properties or functions. Is there any way to "require" it (compile it) from that string into an object, such that I can use it? (Also, I don't want to cache it like
require()
does.)

Answer

Here's a very simple example using vm.runInThisContext():

const vm = require('vm');

let code = `
exports['default'] = function() {
  console.log('hello world');
}
`

global.exports = {}; // this is what `exports` in the code will refer to
vm.runInThisContext(code);

global.exports.default(); // "hello world"

Or, if you don't want to use globals, you can achieve something similar using eval:

let sandbox     = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;

eval(wrappedCode);

sandbox.default(); // "hello world"

Both methods assume that the code you're feeding to it is "safe", because they will both allow running arbitrary code.