script.runInNewContext([contextObject[, options]])
contextObject<Object> | <undefined> 可以是vm.constants.DONT_CONTEXTIFY或者将被 情境化 的对象。如果为undefined,将会创建一个空的 contextified 对象以保证向后兼容性。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);