虚拟机(执行 JavaScript)
¥VM (executing JavaScript)
¥Stability: 2 - Stable
源代码: lib/vm.js
node:vm
模块允许在 V8 虚拟机上下文中编译和运行代码。
¥The node:vm
module enables compiling and running code within V8 Virtual
Machine contexts.
node:vm
模块不是安全机制。不要用它来运行不受信任的代码。
¥The node:vm
module is not a security
mechanism. Do not use it to run untrusted code.
JavaScript 代码可以立即编译并运行,也可以编译、保存并稍后运行。
¥JavaScript code can be compiled and run immediately or compiled, saved, and run later.
常见的用例是在不同的 V8 上下文中运行代码。这意味着被调用的代码与调用代码具有不同的全局对象。
¥A common use case is to run the code in a different V8 Context. This means invoked code has a different global object than the invoking code.
可以通过 contextifying 对象提供上下文。调用的代码将上下文中的任何属性视为全局变量。由调用的代码引起的对全局变量的任何更改都反映在上下文对象中。
¥One can provide the context by contextifying an object. The invoked code treats any property in the context like a global variable. Any changes to global variables caused by the invoked code are reflected in the context object.
const vm = require('node:vm');
const x = 1;
const context = { x: 2 };
vm.createContext(context); // Contextify the object.
const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the context.
// Initially, x has the value 2 because that is the value of context.x.
vm.runInContext(code, context);
console.log(context.x); // 42
console.log(context.y); // 17
console.log(x); // 1; y is not defined.