vm.runInThisContext()

vm.runInThisContext(code[, options])

vm.runInThisContext() compiles code, runs it 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 vm.runInThisContext() and eval() to run the same code:

const vm = require('vm');
var localVar = 'initial value';

const vmResult = vm.runInThisContext('localVar = "vm";');
console.log('vmResult: ', vmResult);
console.log('localVar: ', localVar);

const evalResult = eval('localVar = "eval";');
console.log('evalResult: ', evalResult);
console.log('localVar: ', localVar);

// vmResult: 'vm', localVar: 'initial value'
// evalResult: 'eval', localVar: 'eval'

vm.runInThisContext() does not have access to the local scope, so localVar is unchanged. eval() does have access to the local scope, so localVar is changed.

In this way vm.runInThisContext() is much like an indirect eval() call, e.g. (0,eval)('code'). However, it also has the following additional options:

  • 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. Will capture both syntax errors from compiling code and runtime errors thrown by executing the compiled code. Defaults to true.
  • timeout: a number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.
doc_Nodejs
2016-04-30 04:43:12
Comments
Leave a Comment

Please login to continue.