vm.runInNewContext()

vm.runInNewContext(code[, sandbox][, options])

vm.runInNewContext() compiles code, contextifies sandbox if passed or creates a new contextified sandbox if it's omitted, and then runs the code with the sandbox as the global object and returns the result.

vm.runInNewContext() takes the same options as vm.runInThisContext().

Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.

const util = require('util');
const vm = require('vm');

const sandbox = {
  animal: 'cat',
  count: 2
};

vm.runInNewContext('count += 1; name = "kitty"', sandbox);
console.log(util.inspect(sandbox));

// { animal: 'cat', count: 3, name: 'kitty' }

Note that running untrusted code is a tricky business requiring great care. vm.runInNewContext() is quite useful, but safely running untrusted code requires a separate process.

doc_Nodejs
2016-04-30 04:43:11
Comments
Leave a Comment

Please login to continue.