vm.runInNewContext(code[, contextObject[, options]])
code<string> 用于编译和运行的 JavaScript 代码。contextObject<Object> 一个将被 情境化 的对象。如果为undefined,将创建一个新对象。options<Object> | <string>filename<string> 指定此脚本生成的堆栈跟踪中使用的文件名。默认值:'evalmachine.<anonymous>'。lineOffset<number> 指定此脚本生成的堆栈跟踪中显示的行号偏移。默认值:0。columnOffset<number> 指定此脚本生成的堆栈跟踪中显示的首行列偏移量。默认值:0。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>cachedData<Buffer> | <TypedArray> | <DataView> 提供了一个可选的Buffer、TypedArray或DataView,其中包含所提供源代码的 V8 代码缓存数据。importModuleDynamically<Function> 在评估此模块时被调用,当调用import()时使用。如果未指定此选项,调用import()将会因ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING而被拒绝。此选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。specifier<string> 传递给import()的指定符script<vm.Script>- 'importAssertions' <Object> 'assert' 值传递给
optionsExpression可选参数,若未提供值则为空对象。 - 返回值:<Module Namespace Object> | <vm.Module> 推荐返回
vm.Module,以便利用错误跟踪,并避免包含then函数导出的命名空间出现问题。
microtaskMode<string> 如果设置为afterEvaluate,微任务(通过Promise和async function调度的任务)将在脚本运行后立即执行。在这种情况下,它们会包含在timeout和breakOnSigint的作用域中。
- 返回:<any> 脚本中最后执行的语句的结果。
vm.runInNewContext() 首先将给定的 contextObject 上下文化(如果传入 undefined,则会创建一个新的 contextObject),然后编译 code,在创建的上下文中运行它,最后返回结果。运行代码时无法访问本地作用域。
🌐 The vm.runInNewContext() first contextifies the given contextObject (or
creates a new contextObject if passed as undefined), compiles the code,
runs it within the created context, then returns the result. Running code
does not have access to the local scope.
如果 options 是字符串,那么它指定文件名。
🌐 If options is a string, then it specifies the filename.
下面的示例编译并执行代码,该代码会递增一个全局变量并设置一个新的变量。这些全局变量包含在 contextObject 中。
🌐 The following example compiles and executes code that increments a global
variable and sets a new one. These globals are contained in the contextObject.
const vm = require('node:vm');
const contextObject = {
animal: 'cat',
count: 2
};
vm.runInNewContext('count += 1; name = "kitty"', contextObject);
console.log(contextObject);
// Prints: { animal: 'cat', count: 3, name: 'kitty' }