Node.js | Constructor: new vm.Script() Method

The Constructor: new vm.Script() method creates a new vm.Script object and compiles the stated code but it does not run the code. Moreover, the compiled vm.Script can run afterwards as many times as required. Here, the code is not connected to any global object, rather it’s connected before each run, just for that particular run.

Syntax:

Constructor: new vm.Script( code, options )

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

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

Below examples illustrate the use of Constructor: new vm.Script() in Node.js:

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// Constructor: new vm.Script() method
  
// Including vm and util module
const util = require('util');
const vm = require('vm');
  
// Creating context
const context = {
  number: 2
};
  
// Calling the constructor
const script = new vm.Script('Type = "Int"; number *= 2;');
  
// Contextifying object
vm.createContext(context);
  
// Calling runInContext method
script.runInContext(context);
  
// Displays output
console.log(context);

chevron_right


Output:

{ number: 4, Type: 'Int' }

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// Constructor: new vm.Script() method
  
// Including vm and util module
const util = require('util');
const vm = require('vm');
  
// Creating context
const context = {
  value: 1.0
};
  
// Calling the constructor
const script = new vm.Script('Type = "Float"; value += 2*0.1;');
  
// Contextifying object
vm.createContext(context);
  
// Calling runInContext method
script.runInContext(context);
  
// Displays output
console.log(context);

chevron_right


Output:

{ value: 1.2, Type: 'Float' }

Reference: https://nodejs.org/api/vm.html#vm_constructor_new_vm_script_code_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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.