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').】