vm.runInContext(code, contextifiedSandbox[, options])
vm.runInContext()
compiles code
, then runs it in contextifiedSandbox
and returns the result. Running code does not have access to local scope. The contextifiedSandbox
object must have been previously contextified via vm.createContext()
; it will be used as the global object for code
.
vm.runInContext()
takes the same options as vm.runInThisContext()
.
Example: compile and execute different scripts in a single existing context.
const util = require('util'); const vm = require('vm'); const sandbox = { globalVar: 1 }; vm.createContext(sandbox); for (var i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', sandbox); } console.log(util.inspect(sandbox)); // { globalVar: 1024 }
Note that running untrusted code is a tricky business requiring great care. vm.runInContext()
is quite useful, but safely running untrusted code requires a separate process.
Please login to continue.