Open In App

Node.js vm.runInThisContext() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The vm.runInThisContext() method compiles the code, runs it inside the context of the current global and then returns the output. Moreover, the running code has no access to the local scope, but have access to the current global object. Syntax:

vm.runInThisContext( code, options )

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

  • code: It is the JavaScript code to compile and run.
  • options: It is an optional parameter and it returns an Object or string and if it is a string, then it defines the filename which returns string.

Return Value: It returns the result of the very last statement executed in the script. Below examples illustrate the use of vm.runInThisContext() method in Node.js: Example 1: 

javascript




// Node.js program to demonstrate the    
// runInThisContext() method
  
// Including vm module
const vm = require('vm');
  
// Declaring local variable
let localVar = 'GfG';
  
// Calling runInThisContext method
const vmresult =
 vm.runInThisContext('localVar = "Geeks";');
  
// Prints output for vmresult
console.log(`vmresult: '${vmresult}',
              localVar: '${localVar}'`);
  
// Constructing eval
const evalresult = eval('localVar = "CS";');
  
// Prints output for evalresult
console.log(`evalresult: '${evalresult}',
                localVar: '${localVar}'`);


Output: So, the vm.runInThisContext() method have no access to the local scope hence, localVar is unchanged here.

vmresult: 'Geeks', 
                   localVar: 'GfG'
evalresult: 'CS', 
                localVar: 'GfG'

Example 2: 

javascript




// Node.js program to demonstrate the    
// runInThisContext() method
  
// Including vm module
const vm = require('vm');
  
// Declaring local variable and assigning
// it an integer
let localVar = 6;
  
// Calling runInThisContext method
const vmresult =
vm.runInThisContext('localVar = 9;');
  
// Prints output for vmresult
console.log(`vmresult: '${vmresult}',
             localVar: '${localVar}'`);
  
// Constructing eval
const evalresult = eval('localVar = 11;');
  
// Prints output for evalresult
console.log(`evalresult: '${evalresult}',
                localVar: '${localVar}'`);


Output:

vmresult: '9', 
                  localVar: '6'
evalresult: '11',
                localVar: '6'

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



Last Updated : 26 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads