# Executing JavaScript Stability: 2 - Stable You can access this module with: var vm = require('vm'); JavaScript code can be compiled and run immediately or compiled, saved, and run later. ## vm.runInThisContext(code[, options]) `vm.runInThisContext()` compiles `code`, runs it and returns the result. Running code does not have access to local scope, but does have access to the current `global` object. Example of using `vm.runInThisContext` and `eval` to run the same code: var localVar = 'initial value'; var vmResult = vm.runInThisContext('localVar = "vm";'); console.log('vmResult: ', vmResult); console.log('localVar: ', localVar); var evalResult = eval('localVar = "eval";'); console.log('evalResult: ', evalResult); console.log('localVar: ', localVar); // vmResult: 'vm', localVar: 'initial value' // evalResult: 'eval', localVar: 'eval' `vm.runInThisContext` does not have access to the local scope, so `localVar` is unchanged. `eval` does have access to the local scope, so `localVar` is changed. In this way `vm.runInThisContext` is much like an [indirect `eval` call][1], e.g. `(0,eval)('code')`. However, it also has the following additional options: - `filename`: allows you to control the filename that shows up in any stack traces produced. - `displayErrors`: whether or not to print any errors to stderr, with the line of code that caused them highlighted, before throwing an exception. Will capture both syntax errors from compiling `code` and runtime errors thrown by executing the compiled code. Defaults to `true`. - `timeout`: a number of milliseconds to execute `code` before terminating execution. If execution is terminated, an `Error` will be thrown. [1]: http://es5.github.io/#x10.4.2 ## vm.createContext([sandbox]) If given a `sandbox` object, will "contextify" that sandbox so that it can be used in calls to `vm.runInContext` or `script.runInContext`. Inside scripts run as such, `sandbox` will be the global object, retaining all its existing properties but also having the built-in objects and functions any standard [global object][2] has. Outside of scripts run by the vm module, `sandbox` will be unchanged. If not given a sandbox object, returns a new, empty contextified sandbox object you can use. This function is useful for creating a sandbox that can be used to run multiple scripts, e.g. if you were emulating a web browser it could be used to create a single sandbox representing a window's global object, then run all `