Open In App

Node.js script.runInContext() Method

The script.runInContext() method is used to run the compiled code which is present inside the vm.Script object within the stated contextifiedObject and returns the output. However, the running code has no access to the local scope.

Syntax:



script.runInContext( contextifiedObject, options )

Parameters: This method accept two 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 script.runInContext() method in Node.js:

Example 1:




// Node.js program to demonstrate the     
// script.runInContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Constructing context
const contextobj = {
  name: 'Nidhi',
  articles: 60
};
  
// Constructing script
const script = new vm.Script('articles *= 10;');
  
// Contextifying object
vm.createContext(contextobj);
  
// Calling runInContext method
script.runInContext(contextobj);
  
// Displays output
console.log(contextobj);

Output:

{ name: 'Nidhi', articles: 600 }

Here, articles is 600 as (60*10 = 600).

Example 2:




// Node.js program to demonstrate the     
// script.runInContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Constructing context
const contextobj = { globalVar: 6 };
  
// Constructing script
const script = new vm.Script('globalVar += 12;');
  
// Contextifying object
vm.createContext(contextobj);
  
// Calling for loop
for (let i = 1; i < 4; i++) {
  
// Calling runInContext method
script.runInContext(contextobj);
}
  
// Displays output
console.log("The output is: ", contextobj);

Output:

The output is:  { globalVar: 42 }

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


Article Tags :