Open In App

Node.js vm.runInContext() Method

The vm.runInContext() method is used to compile the code. It runs the code inside the context of the contextifiedObject and then returns the output. Moreover, the running code have no access to the local scope and, the contextifiedObject object be contextified formerly using vm.createContext() method.

Syntax:



vm.runInContext( code, contextifiedObject, 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.runInContext() method in Node.js:

Example 1:




// Node.js program to demonstrate the     
// vm.runInContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Defining Context object
const contextobj = { count: 8 }
  
// Contextifying stated object
// using createContext method
vm.createContext(contextobj);
  
// Compiling code by using runInContext
// method with its parameter
vm.runInContext('count *= 4;', contextobj, 'file.vm');
  
// Displays output
console.log("The output is: ", contextobj);

Output:

The output is:  { count: 32 }

Here, the count is 32 in output as (8*4 = 32).

Example 2:




// Node.js program to demonstrate the     
// vm.runInContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Creating object
cobj = {
         name_of_school: 'M.B.V',
         number_of_students: 10
    },
  
// Contexifying object
context = vm.createContext(cobj);
  
// Calling runInContext method
vm.runInContext('number_of_students *= 3;',
             cobj, 'myfile.vm');
  
// Displays object
console.log(cobj);

Output:

{ name_of_school: 'M.B.V', number_of_students: 30 }

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


Article Tags :