script.runInThisContext([options])
在当前 global
对象的上下文中运行 vm.Script
包含的编译代码。
运行代码无权访问本地作用域,但确实有访问当前 global
对象的权限。
下面的示例编译了增加 global
变量的代码,然后多次执行该代码:
const vm = require('vm');
global.globalVar = 0;
const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
for (let i = 0; i < 1000; ++i) {
script.runInThisContext();
}
console.log(globalVar);
// 1000
options
<Object>displayErrors
<boolean> Whentrue
, if anError
occurs while compiling thecode
, the line of code causing the error is attached to the stack trace. Default:true
.timeout
<integer> Specifies the number of milliseconds to executecode
before terminating execution. If execution is terminated, anError
will be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> Iftrue
, the execution will be terminated whenSIGINT
(Ctrl+C) is received. Existing handlers for the event that have been attached viaprocess.on('SIGINT')
will be disabled during script execution, but will continue to work after that. If execution is terminated, anError
will be thrown. Default:false
.
- Returns: <any> the result of the very last statement executed in the script.
Runs the compiled code contained by the vm.Script
within the context of the
current global
object. Running code does not have access to local scope, but
does have access to the current global
object.
The following example compiles code that increments a global
variable then
executes that code multiple times:
const vm = require('vm');
global.globalVar = 0;
const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
for (let i = 0; i < 1000; ++i) {
script.runInThisContext();
}
console.log(globalVar);
// 1000