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:
const util = require( 'util' );
const vm = require( 'vm' );
const context = {
number: 2
};
const script = new vm.Script( 'Type = "Int"; number *= 2;' );
vm.createContext(context);
script.runInContext(context);
console.log(context);
|
Output:
{ number: 4, Type: 'Int' }
Example 2:
const util = require( 'util' );
const vm = require( 'vm' );
const context = {
value: 1.0
};
const script = new vm.Script( 'Type = "Float"; value += 2*0.1;' );
vm.createContext(context);
script.runInContext(context);
console.log(context);
|
Output:
{ value: 1.2, Type: 'Float' }
Reference: https://nodejs.org/api/vm.html#vm_constructor_new_vm_script_code_options
Last Updated :
11 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...