Node.js | script.runInThisContext() Method

The script.runInThisContext() method runs the compiled code present inside the vm.Script within the context of the current global object. Moreover, running code has no access to local scope, but it has access to the current global object.

Syntax:

script.runInThisContext( options )

Parameters: This method accepts single parameter options which is optional and returns Object. The options can be displayErrors, timeout, and breakOnSigint.



Return Value: It returns the result of the very last statement executed in the script.

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// script.runInThisContext() method
  
// Including vm module
const vm = require('vm');
  
// Defining code
let code = 'console.log("I am an author?");';
  
// Defining script
let script = new vm.Script(code);
  
// Calling runInThisContext method
script.runInThisContext();

chevron_right


Output:

I am an author?

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// script.runInThisContext() method
  
// Including vm module
const vm = require('vm');
  
// Defining x and y
 var x = 40; var y = 17;
   
// Adding x and y
const z = x + y;
  
// Dwfining code
let code = console.log(z);
  
// Defining script
let script = new vm.Script(code);
  
// Calling runInThisContext method
script.runInThisContext();

chevron_right


Output:

57

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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.