Execute JavaScript code stored as a string
You can execute it using a function. Example:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
With the eval
function, like:
eval("my script here");
The eval
function will evaluate a string that is passed to it.
But the use of eval
is super dangerous AND slow, so use with caution.
For users that are using node and that are concerned with the context implications of eval()
nodejs offers vm
. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.
Taking things a step further is vm2
which hardens vm
allowing the vm to run untrusted code.
https://nodejs.org/api/vm.html - Official nodejs/vm
https://github.com/patriksimek/vm2 - Extended vm2
const vm = require('vm');
const x = 1;
const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.
const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);
console.log(sandbox.x); // 42
console.log(sandbox.y); // 17
console.log(x); // 1; y is not defined.