Open In App

Node.js vm.runInNewContext() Method

The vm.runInNewContext() method contextifies the stated contextObject, compiles the code written and runs it inside the context created and then after all this returns the output. However, the running code have no access to the local scope.

Syntax:



vm.runInNewContext( code, contextObject, options )

Parameters: This method accept three parameters as mentioned above and described below:

Return Value: It returns the result of the very last statement executed in the script.

Below examples illustrate the use of vm.runInNewContext() method in Node.js:

Example 1:




// Node.js program to demonstrate the     
// vm.runInNewContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Creating contextObject
const obj = {
  portal: 'GeeksforGeeks',
  authors: 30
};
  
// Calling runInNewContext method
// with its parameters
vm.runInNewContext('authors *= 3;', obj);
  
// Displays output
console.log(obj);

Output:

{ portal: 'GeeksforGeeks', authors: 90 }

Here, authors in the output is 90 as (30 * 3 = 90).

Example 2:




// Node.js program to demonstrate the     
// vm.runInNewContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Creating contextObject
const contextobj = {localVar: 20};
  
// Calling runInNewContext method
// with its parameters
var x = vm.runInNewContext('localVar +=(3*3);',
            contextobj, 2, 'myfile.vm');
  
// Displays output
console.log(contextobj);
console.log(x);

Output:

{ localVar: 29 }
29

Reference: https://nodejs.org/api/vm.html#vm_vm_runinnewcontext_code_contextobject_options


Article Tags :