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> 提供了一个可选的 BufferTypedArrayDataView,其中包含所提供源代码的 V8 代码缓存数据。
    • importModuleDynamically <Function> 在评估此模块时被调用,当调用 import() 时使用。如果未指定此选项,调用 import() 将会因 ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING 而被拒绝。此选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。
    • 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' }