vm.runInThisContext(code[, options])
code<string> 用于编译和运行的 JavaScript 代码。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,接收SIGINT(Ctrl+C)将终止执行并抛出Error。通过process.on('SIGINT')附加的事件现有处理程序在脚本执行期间被禁用,但在此之后仍然有效。默认值:false。cachedData<Buffer> | <TypedArray> | <DataView> 提供可选的Buffer或TypedArray,或者DataView,用于所提供源的 V8 代码缓存数据。importModuleDynamically<Function> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> 用于指定在调用import()时,该脚本在评估过程中模块应如何加载。此选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。有关详细信息,请参见 在编译 API 中支持动态import()。
- 返回:<any> 脚本中最后执行的那条语句的结果。
vm.runInThisContext() 会编译 code,在当前 global 的上下文中运行它,并返回结果。运行的代码无法访问本地作用域,但可以访问当前的 global 对象。
如果 options 是字符串,那么它指定文件名。
🌐 If options is a string, then it specifies the filename.
下面的示例说明了如何同时使用 vm.runInThisContext() 和 JavaScript 的 eval() 函数来运行相同的代码:
🌐 The following example illustrates using both vm.runInThisContext() and
the JavaScript eval() function to run the same code:
const vm = require('node:vm');
let localVar = 'initial value';
const vmResult = vm.runInThisContext('localVar = "vm";');
console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);
// Prints: vmResult: 'vm', localVar: 'initial value'
const evalResult = eval('localVar = "eval";');
console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);
// Prints: evalResult: 'eval', localVar: 'eval' 因为 vm.runInThisContext() 无法访问本地作用域,localVar 保持不变。相比之下,直接调用 eval() 是可以访问本地作用域的,所以 localVar 的值会被修改。这样一来,vm.runInThisContext() 很像一个 间接 eval() 调用,例如 (0,eval)('code')。
🌐 Because vm.runInThisContext() does not have access to the local scope,
localVar is unchanged. In contrast, a direct eval() call does have access
to the local scope, so the value localVar is changed. In this way
vm.runInThisContext() is much like an indirect eval() call, e.g.
(0,eval)('code').