Node.js vm.createContext() Method
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 accepts two parameters as mentioned above 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:
Javascript
const util = require( 'util' );
const vm = require( 'vm' );
global.globalVar = 10;
const object = { globalVar: 4 };
vm.createContext(object);
vm.runInContext( 'globalVar /= 2;' , object);
console.log( "Context: " , object);
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:
Javascript
const util = require( 'util' );
const vm = require( 'vm' );
global.globalVar = 5;
const object = { globalVar: 20 };
vm.createContext(object);
vm.runInContext( 'globalVar += 2;' , object);
console.log( "Context: " , object);
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
Last Updated :
12 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...