vm.runInContext(code, contextifiedObject[, options])


  • code <string> 用于编译和运行的 JavaScript 代码。
  • contextifiedObject <Object> 情境化 对象将在 code 被编译和运行时作为 global 使用。
  • 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
    • 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 函数导出的命名空间出现问题。
  • 返回:<any> 脚本中最后执行的那条语句的结果。

vm.runInContext() 方法会编译 code,在 contextifiedObject 的上下文中运行它,然后返回结果。运行的代码无法访问本地作用域。contextifiedObject 对象必须之前使用 vm.createContext() 方法被 情境化

🌐 The vm.runInContext() method compiles code, runs it within the context of the contextifiedObject, then returns the result. Running code does not have access to the local scope. The contextifiedObject object must have been previously contextified using the vm.createContext() method.

如果 options 是字符串,那么它指定文件名。

🌐 If options is a string, then it specifies the filename.

以下示例使用单个 情境化 对象编译并执行不同的脚本:

🌐 The following example compiles and executes different scripts using a single contextified object:

const vm = require('node:vm');

const contextObject = { globalVar: 1 };
vm.createContext(contextObject);

for (let i = 0; i < 10; ++i) {
  vm.runInContext('globalVar *= 2;', contextObject);
}
console.log(contextObject);
// Prints: { globalVar: 1024 }