script.runInNewContext([contextObject[, options]])


  • contextObject <Object> 一个将会是 情境化 的对象。如果 undefined,将会创建一个新对象。
  • options <Object>
    • 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
    • microtaskMode <string> 如果设置为 afterEvaluate,微任务(通过 Promiseasync function 调度的任务)将在脚本运行后立即执行。在这种情况下,它们会包含在 timeoutbreakOnSigint 范围内。
  • 返回:<any> 脚本中最后执行的那条语句的结果。

首先将给定的 contextObject 置于上下文中,然后在创建的上下文中运行 vm.Script 对象包含的已编译代码,并返回结果。运行的代码无法访问本地作用域。

🌐 First contextifies the given contextObject, runs the compiled code contained by the vm.Script object within the created context, and returns the result. Running code does not have access to local scope.

以下示例编译代码,该代码设置一个全局变量,然后在不同的上下文中多次执行该代码。全局变量在每个独立的 context 中设置并包含。

🌐 The following example compiles code that sets a global variable, then executes the code multiple times in different contexts. The globals are set on and contained within each individual context.

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

const script = new vm.Script('globalVar = "set"');

const contexts = [{}, {}, {}];
contexts.forEach((context) => {
  script.runInNewContext(context);
});

console.log(contexts);
// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]