1

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.)

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.