script.runInThisContext([options])
-
options
<Object>-
displayErrors
<boolean> 当为true
时,如果编译code
时出现Error
,则导致错误的代码行会附加到堆栈跟踪中。默认值:true
。¥
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> 指定终止执行前执行code
的毫秒数。如果执行终止,则将抛出Error
。此值必须是严格的正整数。¥
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> 如果是true
,接收SIGINT
(Ctrl+C)将终止执行并抛出Error
。已通过process.on('SIGINT')
附加的事件的现有句柄在脚本执行期间被禁用,但在此之后继续工作。默认值:false
。¥
breakOnSigint
<boolean> Iftrue
, receivingSIGINT
(Ctrl+C) will terminate execution and throw anError
. Existing handlers for the event that have been attached viaprocess.on('SIGINT')
are disabled during script execution, but continue to work after that. Default:false
.
-
-
返回:<any> 脚本中最后一条语句执行的结果。
¥Returns: <any> the result of the very last statement executed in the script.
在当前 global
对象的上下文中运行 vm.Script
包含的编译代码。运行代码无权访问局部作用域,但可以访问当前 global
对象。
¥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.
下面的示例编译了增加 global
变量的代码,然后多次执行该代码:
¥The following example compiles code that increments a global
variable then
executes that code multiple times:
const vm = require('node: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