Open In App

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.

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


Article Tags :