Skip to content

node-vm-runinthiscontext

The vm package in node enables compiling and running code within V8 virtual machine contexts. Contexts allow you to sandbox scope when executing code. The runInThisContext function will execute the code within the context of the current global object, which is essentially the same thing as running eval.

Examples

Insecure Example

const vm = require('vm');

global.globalVar = 0;

const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });

for (let i = 0; i < 1000; ++i) {
    script.runInThisContext();
}

Secure Example

const vm = require('vm');

const script = new vm.Script('globalVar = "set"');

const contexts = [{}, {}, {}];
contexts.forEach((context) => {
    script.runInNewContext(context);
});