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> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> 用于指定在调用 import() 时,该脚本在评估过程中模块应如何加载。此选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。有关详细信息,请参见 在编译 API 中支持动态 import()

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 }