If you need to dynamically (I mean at runtime) evaluate javascript contained in a string, you should use the Function constructor.
For example:
var code = "function sayHello() {return 'hello !';} module.exports = sayHello()";
var executor = new Function(code);
try {
// the code in executor will search for global variables into global scope.
global.module = {};
executor();
// your results are here
console.log(global.module);
} catch (err) {
console.error('Failed to execute code:', err);
}
You have to understand that:
- the dynamic code is executed within the global scope. That is, not access to local variables
- global variable in the dynamic code must be initialized before execution
- variables can also be passed as argument of the function itself
- return of the dynamic code will be accessible as return of the function
An example of variable passing and return:
var code = "function sayHello() {return something;} console.log(sayHello()); return true";
// Indicate that the something variable inside the code is in fact an argument
var executor = new Function("something", code);
try {
// pass 'hi!' as 'something' argument, display return
console.log(executor("hi !"));
} catch (e) {
console.error('fail', e);
}
Outputs :
> hi !
> true
Don't use eval()
(remember: eval is evil), because it will give access to your local scope, and can became a breach in your application.