node:vm надає API компіляції скриптів і контекстів у формі Node.
Контекст не є межею безпеки. Вбудовані об’єкти (intrinsics) спільні з realm хоста. Для недовіреного коду використовуйте ізоляцію процесів і файлової системи.
| Експорт | Призначення |
|---|---|
Script | Скомпілювати код і запустити його в цьому контексті або в контексті пісочниці. |
createContext() / isContext() | Перетворити об’єкт на контекст і перевірити його позначку. |
compileFunction() | Скомпілювати тіло функції. |
runInThisContext() | Обчислити в поточній глобальній області видимості. |
runInContext() | Обчислити щодо об’єкта-контексту. |
runInNewContext() | Обчислити щодо нового об’єкта пісочниці. |
measureMemory() | Повернути Promise з результатом вимірювання пам’яті. |
constants | Константи VM. |
const vm = require("node:vm");
const sandbox = { x: 2 };
vm.createContext(sandbox);
vm.runInContext("x + 3", sandbox); // 5SourceTextModule надає лише обмежений життєвий цикл і не забезпечує повного
зв’язування та обчислення модулів.
Див. також
Reference
Status: Full · 80 of 95 suite tests pass (84.2%) · since 1.1.0
Exports
| Export | Kind | Status | Notes |
|---|---|---|---|
Script | class | Full | runInThisContext(), runInNewContext() |
createContext() | function | Full | Creates a new execution context (sandbox) |
runInNewContext() | function | Full | Compiles code, creates a new context, and runs the code in that context |
runInThisContext() | function | Full | Compiles and runs code within the current global context |
isContext() | function | Full | Returns whether the given object is a contextified sandbox |
Tests: node-api node:vm: 80 pass, 15 fail, 0 error, 3 skipped. Failing: test-vm-basic.js, test-vm-codegen.js, test-vm-context-dont-contextify.js, test-vm-function-declaration.js, test-vm-global-property-prototype.js, test-vm-global-setter.js, test-vm-harmony-symbols.js, test-vm-module-after-evaluate.js, and 7 more.