Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:




// 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);

Output:

{ number: 4, Type: 'Int' }

Example 2:




// 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);

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
Last Updated : 11 Oct, 2021
Like Article
Save Article
Similar Reads
Related Tutorials