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:
javascript
Output:
javascript
Output:
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.
// 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);
{ 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);
{ value: 1.2, Type: 'Float' }
Reference: https://nodejs.org/api/vm.html#vm_constructor_new_vm_script_code_options