script.runInThisContext()

script.runInThisContext([options])

Similar to vm.runInThisContext() but a method of a precompiled Script object. script.runInThisContext() runs script's compiled code and returns the result. Running code does not have access to local scope, but does have access to the current global object.

Example of using script.runInThisContext() to compile code once and run it multiple times:

const vm = require('vm');

global.globalVar = 0;

const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });

for (var i = 0; i < 1000; ++i) {
  script.runInThisContext();
}

console.log(globalVar);

// 1000

The options for running a script are:

  • filename: allows you to control the filename that shows up in any stack traces produced.
  • lineOffset: allows you to add an offset to the line number that is displayed in stack traces
  • columnOffset: allows you to add an offset to the column number that is displayed in stack traces
  • displayErrors: whether or not to print any errors to stderr, with the line of code that caused them highlighted, before throwing an exception. Applies only to runtime errors executing the code; it is impossible to create a Script instance with syntax errors, as the constructor will throw.
  • timeout: a number of milliseconds to execute the script before terminating execution. If execution is terminated, an Error will be thrown.
doc_Nodejs
2016-04-30 04:42:16
Comments
Leave a Comment

Please login to continue.