vm.runInNewContext(code[, contextObject[, options]])


  • code <string> 用于编译和运行的 JavaScript 代码。
  • contextObject <Object> | <undefined> 要么是 vm.constants.DONT_CONTEXTIFY,要么是将成为 情境化 的对象。如果是 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> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> 用于指定在调用 import() 时,该脚本在评估过程中模块应如何加载。此选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。有关详细信息,请参见 在编译 API 中支持动态 import()
    • microtaskMode <string> 如果设置为 afterEvaluate,微任务(通过 Promiseasync function 调度的任务)将在脚本运行后立即执行。在这种情况下,它们会包含在 timeoutbreakOnSigint 范围内。
  • 返回:<any> 脚本中最后执行的那条语句的结果。

此方法是 (new vm.Script(code, options)).runInContext(vm.createContext(options), options) 的快捷方式。如果 options 是字符串,则它指定文件名。

🌐 This method is a shortcut to (new vm.Script(code, options)).runInContext(vm.createContext(options), options). If options is a string, then it specifies the filename.

它同时做几件事:

🌐 It does several things at once:

  1. 创建一个新的上下文。
  2. 如果 contextObject 是一个对象,用新的上下文 使具上下文 它。如果 contextObject 未定义,则创建一个新对象并 使具上下文 它。如果 contextObjectvm.constants.DONT_CONTEXTIFY,则不要 使具上下文 任何东西。
  3. 将代码编译为 vm.Script
  4. 在创建的上下文中运行编译后的代码。代码无法访问调用此方法的作用域。
  5. 返回结果。

下面的示例编译并执行代码,该代码会递增一个全局变量并设置一个新的变量。这些全局变量包含在 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' }

// 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 frozenContext = vm.runInNewContext('Object.freeze(globalThis); globalThis;', vm.constants.DONT_CONTEXTIFY);