Skip to content
Related Articles

Related Articles

Node.js | vm.createContext() Method
  • Last Updated : 15 Apr, 2020

The vm.createContext() method is used to create a single context that can be utilized to run more than one scripts. Moreover, if the stated contextObject is neglected then a new, empty contextified object is returned. However, if contextObject is stated then, this method will ready that object so that it can be used in calling vm.runInContext() or script.runInContext(). Where the contextObject will be the global object inside such scripts which can retain its active properties. And outside the scripts, it run by vm module and even global variables remain constant.

Syntax:

vm.createContext( contextObject, options )

Parameters: This method accept two parameters as mentioned avobe and described below:

  • contextObject: It is the object which is contextified.
  • options: It is optional and returns Object.

Return Value: It returns contextified object.

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



Example 1:




// Node.js program to demonstrate the     
// vm.createContext([contextObject[, options]])
// method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Assigning value to the global variable
global.globalVar = 10;
  
// Defining Context object
const object = { globalVar: 4 };
  
// Contextifying stated object
// using createContext method
vm.createContext(object);
  
// Compiling code
vm.runInContext('globalVar /= 2;', object);
  
// Displays the context
console.log("Context: ", object);
  
// Dsiplays value of global variable
console.log("Global Variable is ", global.globalVar);

Output: Here, globalVar in the context is 2 in output as (4/2 = 2) but the value of globalVar is still 10.

Context:  { globalVar: 2 }
Global Variable is  10

Example 2:




// Node.js program to demonstrate the     
// vm.createContext([contextObject[, options]])
// method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Assigning value to the global variable
global.globalVar = 5;
  
// Defining Context object
const object = { globalVar: 20 };
  
// Contextifying stated object
// using createContext method
vm.createContext(object);
  
// Compiling code
vm.runInContext('globalVar += 2;', object);
  
// Displays the context
console.log("Context: ", object);
  
// Dsiplays value of global variable
console.log("Global Variable is ", global.globalVar);

Output: Here, globalVar in the context is 22 in output as (20+2 = 22) but the value of globalVar is still 5.

Context:  { globalVar: 22 }
Global Variable is  5

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :