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.

1
2
3
4
5
6
7
8
9
10
11
12
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
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.