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> 提供了一个可选的 BufferTypedArrayDataView,其中包含所提供源代码的 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 }