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


  • code <string> 将被编译和运行的 JavaScript 代码。
  • contextObject <Object> 一个将会被上下文隔离化的对象。如果是 undefined, 则会生成一个新的对象。
  • options <Object> | <string>
    • filename <string> 定义供脚本生成的堆栈跟踪信息所使用的文件名。默认值: 'evalmachine.<anonymous>'
    • lineOffset <number> 定义脚本生成的堆栈跟踪信息所显示的行号偏移。默认值: 0
    • columnOffset <number> 定义脚本生成的堆栈跟踪信息所显示的列号偏移。默认值: 0
    • displayErrors <boolean> 当值为 true 的时候,假如在解析代码的时候发生错误 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> 为源码提供一个可选的存有 V8 代码缓存数据的 BufferTypedArrayTypedArray。 如果提供了,则 cachedDataRejected 的值将会被设为要么为 true 要么为 false,这取决于 v8 引擎对数据的接受状况。
    • produceCachedData <boolean> 当值为 truecachedData 不存在的时候,V8 将会试图为 code 生成代码缓存数据。 一旦成功,则一个有 V8 代码缓存数据的 Buffer 将会被生成和储存在返回的 vm.Script 实例的 cachedData 属性里。 cachedDataProduced 的值会被设置为 true 或者 false,这取决于代码缓存数据是否被成功生成。 不推荐使用此选项,而应该使用 script.createCachedData()默认值: false
    • importModuleDynamically <Function> 在调用 import() 时评估此模块期间调用。 如果未指定此选项,则对 import() 的调用将拒绝 ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING。 此选项是实验的模块的 API 的一部分,不应被视为稳定。
    • microtaskMode <string> If set to afterEvaluate, microtasks (tasks scheduled through Promises and async functions) will be run immediately after the script has run. They are included in the timeout and breakOnSigint scopes in that case.
  • 返回: <any> 脚本中执行的最后一个语句的结果。

vm.runInNewContext() 首先给指定的 contextObject(若为 undefined,则会新建一个 contextObject)提供一个隔离的上下文, 再在此上下文中执行编译的 code,最后返回结果。 运行中的代码无法获取本地作用域。

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

以下的例子会编译一段代码,该代码会递增一个全局变量,给另外一个全局变量赋值。同时该代码被编译后会被多次执行。全局变量会被置于 contextObject 对象内。

const vm = require('vm');

const contextObject = {
  animal: 'cat',
  count: 2
};

vm.runInNewContext('count += 1; name = "kitty"', contextObject);
console.log(contextObject);
// 打印: { animal: 'cat', count: 3, name: 'kitty' }
  • code <string> The JavaScript code to compile and run.
  • contextObject <Object> An object that will be contextified. If undefined, a new object will be created.
  • options <Object> | <string>
    • filename <string> Specifies the filename used in stack traces produced by this script. Default: 'evalmachine.<anonymous>'.
    • lineOffset <number> Specifies the line number offset that is displayed in stack traces produced by this script. Default: 0.
    • columnOffset <number> Specifies the column number offset that is displayed in stack traces produced by this script. Default: 0.
    • displayErrors <boolean> When true, if an Error occurs while compiling the code, the line of code causing the error is attached to the stack trace. Default: true.
    • timeout <integer> Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown. This value must be a strictly positive integer.
    • breakOnSigint <boolean> If true, receiving SIGINT (Ctrl+C) will terminate execution and throw an Error. Existing handlers for the event that have been attached via process.on('SIGINT') are disabled during script execution, but continue to work after that. Default: false.
    • contextName <string> Human-readable name of the newly created context. Default: 'VM Context i', where i is an ascending numerical index of the created context.
    • contextOrigin <string> Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the url.origin property of a URL object. Most notably, this string should omit the trailing slash, as that denotes a path. Default: ''.
    • contextCodeGeneration <Object>
      • strings <boolean> If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) will throw an EvalError. Default: true.
      • wasm <boolean> If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. Default: true.
    • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or TypedArray, or DataView with V8's code cache data for the supplied source. When supplied, the cachedDataRejected value will be set to either true or false depending on acceptance of the data by V8.
    • produceCachedData <boolean> When true and no cachedData is present, V8 will attempt to produce code cache data for code. Upon success, a Buffer with V8's code cache data will be produced and stored in the cachedData property of the returned vm.Script instance. The cachedDataProduced value will be set to either true or false depending on whether code cache data is produced successfully. This option is deprecated in favor of script.createCachedData(). Default: false.
    • importModuleDynamically <Function> Called during evaluation of this module when import() is called. If this option is not specified, calls to import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. This option is part of the experimental modules API. We do not recommend using it in a production environment.
    • microtaskMode <string> If set to afterEvaluate, microtasks (tasks scheduled through Promises and async functions) will be run immediately after the script has run. They are included in the timeout and breakOnSigint scopes in that case.
  • Returns: <any> the result of the very last statement executed in the script.

The vm.runInNewContext() first contextifies the given contextObject (or creates a new contextObject if passed as undefined), compiles the code, runs it within the created context, then returns the result. Running code does not have access to the local scope.

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

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('vm');

const contextObject = {
  animal: 'cat',
  count: 2
};

vm.runInNewContext('count += 1; name = "kitty"', contextObject);
console.log(contextObject);
// Prints: { animal: 'cat', count: 3, name: 'kitty' }