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,接收 SIGINTCtrl+C)将终止执行并抛出 Error。通过 process.on('SIGINT') 附加的事件现有处理程序在脚本执行期间被禁用,但在此之后仍然有效。默认值: false
    • contextName <string> 新创建上下文的人类可读名称。 默认值: 'VM Context i',其中 i 是已创建上下文的递增数字索引。
    • contextOrigin <string> 起源 对应于为显示目的新创建的上下文。原点应格式化为类似 URL 的形式,但只包括方案、主机和端口(如有必要),类似于 URL 对象的 url.origin 属性的值。最重要的是,该字符串应省略结尾的斜杠,因为斜杠表示路径。默认值: ''
    • contextCodeGeneration <Object>
      • strings <boolean> 如果设置为 false,对 eval 或函数构造器(FunctionGeneratorFunction 等)的任何调用都会抛出 EvalError默认值: true
      • wasm <boolean> 如果设置为 false,则任何尝试编译 WebAssembly 模块的操作都会抛出 WebAssembly.CompileError默认值: true
    • cachedData <Buffer> | <TypedArray> | <DataView> 提供可选的 BufferTypedArray,或者 DataView,用于所提供源的 V8 代码缓存数据。
    • importModuleDynamically <Function> 在评估此模块时调用,当调用 import() 时触发。如果未指定此选项,则对 import() 的调用将被 ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING 拒绝。此选项属于实验性模块 API。我们不推荐在生产环境中使用它。如果未设置 --experimental-vm-modules,此回调将被忽略,对 import() 的调用将被 ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG 拒绝。
      • specifier <string> 传递给 import() 的说明符
      • script <vm.Script>
      • importAttributes <Object> 传递给 [optionsExpression][optionsExpression] 可选参数的 "with" 值,如果未提供值,则为一个空对象。
      • 返回:<Module Namespace Object> | <vm.Module> 建议返回 vm.Module,以便利用错误跟踪,并避免包含 then 函数导出的命名空间出现问题。
    • microtaskMode <string> 如果设置为 afterEvaluate,微任务(通过 Promiseasync function 调度的任务)将在脚本运行后立即执行。在这种情况下,它们会包含在 timeoutbreakOnSigint 范围内。
  • 返回:<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' }