script.runInNewContext([contextObject[, options]])
contextObject<Object> | <undefined> 要么是vm.constants.DONT_CONTEXTIFY,要么是将成为 情境化 的对象。如果是undefined,将创建一个空的上下文化对象以保持向后兼容性。options<Object>displayErrors<boolean> 当true时,如果在编译code时发生Error,导致错误的代码行将附加到堆栈跟踪中。默认值:true。timeout<integer> 指定在终止执行前执行code的毫秒数。如果执行被终止,将抛出Error。此值必须是严格正整数。breakOnSigint<boolean> 如果true,接收SIGINT(Ctrl+C)将终止执行并抛出Error。通过process.on('SIGINT')附加的事件现有处理程序在脚本执行期间被禁用,但在此之后仍然有效。默认值:false。contextName<string> 新创建上下文的人类可读名称。 默认值:'VM Context i',其中i是已创建上下文的递增数字索引。contextOrigin<string> 起源 对应于为显示目的新创建的上下文。原点应格式化为类似 URL 的形式,但只包括方案、主机和端口(如有必要),类似于URL对象的url.origin属性的值。最重要的是,该字符串应省略结尾的斜杠,因为斜杠表示路径。默认值:''。contextCodeGeneration<Object>microtaskMode<string> 如果设置为afterEvaluate,微任务(通过Promise和async function调度的任务)将在脚本运行后立即执行。在这种情况下,它们会包含在timeout和breakOnSigint范围内。
- 返回:<any> 脚本中最后执行的那条语句的结果。
此方法是 script.runInContext(vm.createContext(options), options) 的快捷方式。它一次性完成了几件事:
🌐 This method is a shortcut to script.runInContext(vm.createContext(options), options).
It does several things at once:
- 创建一个新的上下文。
- 如果
contextObject是一个对象,用新的上下文 使具上下文 它。如果contextObject未定义,则创建一个新对象并 使具上下文 它。如果contextObject是vm.constants.DONT_CONTEXTIFY,则不要 使具上下文 任何东西。 - 在创建的上下文中运行
vm.Script对象中包含的已编译代码。该代码无法访问调用此方法时的作用域。 - 返回结果。
以下示例编译代码,该代码设置一个全局变量,然后在不同的上下文中多次执行该代码。全局变量在每个独立的 context 中设置并包含。
🌐 The following example compiles code that sets a global variable, then executes
the code multiple times in different contexts. The globals are set on and
contained within each individual context.
const vm = require('node:vm');
const script = new vm.Script('globalVar = "set"');
const contexts = [{}, {}, {}];
contexts.forEach((context) => {
script.runInNewContext(context);
});
console.log(contexts);
// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
// This would throw if the context is created from a contextified object.
// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary
// global objects that can be frozen.
const freezeScript = new vm.Script('Object.freeze(globalThis); globalThis;');
const frozenContext = freezeScript.runInNewContext(vm.constants.DONT_CONTEXTIFY);