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


  • code <string> 用于编译和运行的 JavaScript 代码。
  • contextObject <Object> | <undefined> 可以是 vm.constants.DONT_CONTEXTIFY 或者将被 情境化 的对象。如果为 undefined,将会创建一个空的 contextified 对象以保证向后兼容性。
  • 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> | <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);