Usage in Deno
import * as mod from "node:vm";
The node:vm
module enables compiling and running code within V8 Virtual
Machine contexts.
The node:vm
module is not a security
mechanism. Do not use it to run untrusted code.
JavaScript code can be compiled and run immediately or compiled, saved, and run later.
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.
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.
import vm from '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.
Classes #
This feature is only available with the --experimental-vm-modules
command
flag enabled.
This feature is only available with the --experimental-vm-modules
command
flag enabled.
This feature is only available with the --experimental-vm-modules
command
flag enabled.
Functions #
Compiles the given code into the provided context (if no context is
supplied, the current context is used), and returns it wrapped inside a
function with the given params
.
Returns true
if the given object
object has been contextified using createContext,
or if it's the global object of a context created using vm.constants.DONT_CONTEXTIFY
.
The vm.runInContext()
method compiles code
, runs it within the context of
the contextifiedObject
, then returns the result. Running code does not have
access to the local scope. The contextifiedObject
object must have been
previously contextified
using the createContext method.
This method is a shortcut to
(new vm.Script(code, options)).runInContext(vm.createContext(options), options)
.
If options
is a string, then it specifies the filename.
vm.runInThisContext()
compiles code
, runs it within the context of the
current global
and returns the result. Running code does not have access to
local scope, but does have access to the current global
object.
Interfaces #
Namespaces #
Type Aliases #
Variables #
This constant, when used as the contextObject
argument in vm APIs, instructs Node.js to create
a context without wrapping its global object with another object in a Node.js-specific manner.
As a result, the globalThis
value inside the new context would behave more closely to an ordinary
one.
A constant that can be used as the importModuleDynamically
option to vm.Script
and vm.compileFunction()
so that Node.js uses the default ESM loader from the main
context to load the requested module.