The vm.runInThisContext() method compiles the code, runs it inside the context of the current global and then returns the output. Moreover, the running code has no access to the local scope, but have access to the current global object.
vm.runInThisContext( code, options )
Parameters: This method accept two parameters as mentioned avobe and described below:
- options: It is an optional parameter and it returns an Object or string and if it is a string, then it defines the filename which returns string.
Return Value: It returns the result of the very last statement executed in the script.
Below examples illustrate the use of vm.runInThisContext() method in Node.js:
Output: So, the vm.runInThisContext() method have no access to the local scope hence, localVar is unchanged here.
vmresult: 'Geeks', localVar: 'GfG' evalresult: 'CS', localVar: 'GfG'
vmresult: '9', localVar: '6' evalresult: '11', localVar: '6'