Open In App

Node.js vm.runInNewContext() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The vm.runInNewContext() method contextifies the stated contextObject, compiles the code written and runs it inside the context created and then after all this returns the output. However, the running code have no access to the local scope.

Syntax:

vm.runInNewContext( code, contextObject, options )

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

  • code: It is the JavaScript code to compile and run.
  • contextObject: It is an object that will be contextified and if it is undefined, a new object will be created.
  • options: It is an optional parameter and returns Object or string and if it is a string, then it defines the filename which returns string.
    It holds the following parameters:

    1. filename: It holds a string that specifies the filename that is used in the stack traces which are generated by this script. It’s default value is ‘evalmachine.anonymous’.
    2. lineOffset: It holds a number that specifies the offset of the line number that is shown in the stack traces which is generated by this script. It’s default value is 0.
    3. columnOffset: It holds a number that specifies the offset of the column number that is shown in the stack traces which are generated by this script. It’s default value is 0.
    4. displayErrors: It holds a Boolean value i.e. true if an error is thrown while compiling the code and the line of code because of which an error is thrown is linked to the stack trace. It’s default value is true.
    5. timeout: It holds an integer value that specifies the number of milliseconds taken in order to execute the stated code before ending the execution. However, if an execution is closed then an error will occur and the value for this must be a positive integer absolutely.
    6. breakOnSigint: It holds a Boolean value. If its true, then the execution will be stopped as soon as SIGINT i.e, (Ctrl+C) is provided. And if the execution is stopped then an error is thrown. Its by default value is false.
    7. contextName: It holds a string. It is human readable names of the newly generated context. And by default it is ‘VM Context i’ where, i is the index of the generated context that is ascending numerically.
    8. contextOrigin: It holds a string. It is the origin that is equivalent to the recently generated context. Moreover, the origin must be formed like a URL. Its by default value is ”.
    9. contextCodeGeneration: It is of type Object.
      It holds following parameters:

      • strings: It holds a Boolean value and if its set to false then any call to function constructors or eval will throw an error i.e, EvalError. Its default value is true.
      • wasm: It holds a Boolean value. And if it is set to false then any tries to compile a WebAssembly module will throw an error i.e, WebAssembly.CompileError. Its by default value is true.
    10. cachedData: It holds a Buffer, TypedArray, or a DataView. It gives an optional Buffer or TypedArray, or DataView for the use of supplied source with the help of V8’s code cache data. After that, the value of the cachedDataRejected can either be set to true or false. It depends upon the reception of data by V8.
    11. produceCachedData: It holds a Boolean value. If its true and cachedData is no more available then V8 tries to output code cache data for the code. If this is accomplished then a buffer with V8’s code cache data is generated and then its consequently stored in the cachedData of the vm.Script instance that is being returned. Moreover, the cachedDataProduced value is either set to true or false depending upon the code cache data. However, this option is deprecated and script.createCachedData() is used instead. Its by default value is false.
    12. importModuleDynamically: It holds a function which is called while evaluating this module when import() method is called. And if this option is not stated then the calls to import() will be rejected with an error.
      It holds following parameters:

      • specifier: It holds a string. It is the specifier passed to the import() method.
      • module: It holds vm.Module. It returns either Module Namespace Object or vm.Module.

Return Value: It returns the result of the very last statement executed in the script.

Below examples illustrate the use of vm.runInNewContext() method in Node.js:

Example 1:




// Node.js program to demonstrate the     
// vm.runInNewContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Creating contextObject
const obj = {
  portal: 'GeeksforGeeks',
  authors: 30
};
  
// Calling runInNewContext method
// with its parameters
vm.runInNewContext('authors *= 3;', obj);
  
// Displays output
console.log(obj);


Output:

{ portal: 'GeeksforGeeks', authors: 90 }

Here, authors in the output is 90 as (30 * 3 = 90).

Example 2:




// Node.js program to demonstrate the     
// vm.runInNewContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Creating contextObject
const contextobj = {localVar: 20};
  
// Calling runInNewContext method
// with its parameters
var x = vm.runInNewContext('localVar +=(3*3);',
            contextobj, 2, 'myfile.vm');
  
// Displays output
console.log(contextobj);
console.log(x);


Output:

{ localVar: 29 }
29

Reference: https://nodejs.org/api/vm.html#vm_vm_runinnewcontext_code_contextobject_options



Last Updated : 11 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads