{ "type": "module", "source": "doc/api/vm.md", "modules": [ { "textRaw": "VM (executing JavaScript)", "name": "vm", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/vm.js
\nThe node:vm
module enables compiling and running code within V8 Virtual\nMachine contexts.
The node:vm
module is not a security\nmechanism. Do not use it to run untrusted code.
JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.
\nA common use case is to run the code in a different V8 Context. This means\ninvoked code has a different global object than the invoking code.
\nOne can provide the context by contextifying an\nobject. The invoked code treats any property in the context like a\nglobal variable. Any changes to global variables caused by the invoked\ncode are reflected in the context object.
\nconst vm = require('node:vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\nvm.createContext(context); // Contextify the object.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the context.\n// Initially, x has the value 2 because that is the value of context.x.\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
",
"classes": [
{
"textRaw": "Class: `vm.Script`",
"type": "class",
"name": "vm.Script",
"meta": {
"added": [
"v0.3.1"
],
"changes": []
},
"desc": "Instances of the vm.Script
class contain precompiled scripts that can be\nexecuted in specific contexts.
When cachedData
is supplied to create the vm.Script
, this value will be set\nto either true
or false
depending on acceptance of the data by V8.\nOtherwise the value is undefined
.
When the script is compiled from a source that contains a source map magic\ncomment, this property will be set to the URL of the source map.
\nimport vm from 'node:vm';\n\nconst script = new vm.Script(`\nfunction myFunc() {}\n//# sourceMappingURL=sourcemap.json\n`);\n\nconsole.log(script.sourceMapURL);\n// Prints: sourcemap.json\n
\nconst vm = require('node:vm');\n\nconst script = new vm.Script(`\nfunction myFunc() {}\n//# sourceMappingURL=sourcemap.json\n`);\n\nconsole.log(script.sourceMapURL);\n// Prints: sourcemap.json\n
"
}
],
"methods": [
{
"textRaw": "`script.createCachedData()`",
"type": "method",
"name": "createCachedData",
"meta": {
"added": [
"v10.6.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
},
"params": []
}
],
"desc": "Creates a code cache that can be used with the Script
constructor's\ncachedData
option. Returns a Buffer
. This method may be called at any\ntime and any number of times.
The code cache of the Script
doesn't contain any JavaScript observable\nstates. The code cache is safe to be saved along side the script source and\nused to construct new Script
instances multiple times.
Functions in the Script
source can be marked as lazily compiled and they are\nnot compiled at construction of the Script
. These functions are going to be\ncompiled when they are invoked the first time. The code cache serializes the\nmetadata that V8 currently knows about the Script
that it can use to speed up\nfuture compilations.
const script = new vm.Script(`\nfunction add(a, b) {\n return a + b;\n}\n\nconst x = add(1, 2);\n`);\n\nconst cacheWithoutAdd = script.createCachedData();\n// In `cacheWithoutAdd` the function `add()` is marked for full compilation\n// upon invocation.\n\nscript.runInThisContext();\n\nconst cacheWithAdd = script.createCachedData();\n// `cacheWithAdd` contains fully compiled function `add()`.\n
"
},
{
"textRaw": "`script.runInContext(contextifiedObject[, options])`",
"type": "method",
"name": "runInContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": [
{
"version": "v6.3.0",
"pr-url": "https://github.com/nodejs/node/pull/6635",
"description": "The `breakOnSigint` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {any} the result of the very last statement executed in the script.",
"name": "return",
"type": "any",
"desc": "the result of the very last statement executed in the script."
},
"params": [
{
"textRaw": "`contextifiedObject` {Object} A [contextified][] object as returned by the `vm.createContext()` method.",
"name": "contextifiedObject",
"type": "Object",
"desc": "A [contextified][] object as returned by the `vm.createContext()` method."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.",
"name": "displayErrors",
"type": "boolean",
"default": "`true`",
"desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.",
"name": "timeout",
"type": "integer",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer."
},
{
"textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.",
"name": "breakOnSigint",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that."
}
]
}
]
}
],
"desc": "Runs the compiled code contained by the vm.Script
object within the given\ncontextifiedObject
and returns the result. Running code does not have access\nto local scope.
The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the context
object.
const vm = require('node:vm');\n\nconst context = {\n animal: 'cat',\n count: 2,\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nvm.createContext(context);\nfor (let i = 0; i < 10; ++i) {\n script.runInContext(context);\n}\n\nconsole.log(context);\n// Prints: { animal: 'cat', count: 12, name: 'kitty' }\n
\nUsing the timeout
or breakOnSigint
options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.
First contextifies the given contextObject
, runs the compiled code contained\nby the vm.Script
object within the created context, and returns the result.\nRunning code does not have access to local scope.
The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual context
.
const vm = require('node:vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst contexts = [{}, {}, {}];\ncontexts.forEach((context) => {\n script.runInNewContext(context);\n});\n\nconsole.log(contexts);\n// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
"
},
{
"textRaw": "`script.runInThisContext([options])`",
"type": "method",
"name": "runInThisContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": [
{
"version": "v6.3.0",
"pr-url": "https://github.com/nodejs/node/pull/6635",
"description": "The `breakOnSigint` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {any} the result of the very last statement executed in the script.",
"name": "return",
"type": "any",
"desc": "the result of the very last statement executed in the script."
},
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.",
"name": "displayErrors",
"type": "boolean",
"default": "`true`",
"desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.",
"name": "timeout",
"type": "integer",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer."
},
{
"textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.",
"name": "breakOnSigint",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that."
}
]
}
]
}
],
"desc": "Runs the compiled code contained by the vm.Script
within the context of the\ncurrent global
object. Running code does not have access to local scope, but\ndoes have access to the current global
object.
The following example compiles code that increments a global
variable then\nexecutes that code multiple times:
const vm = require('node:vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile.",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile."
},
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.If options
is a string, then it specifies the filename.
Creating a new vm.Script
object compiles code
but does not run it. The\ncompiled vm.Script
can be run later multiple times. The code
is not bound to\nany global object; rather, it is bound before each run, just for that run.
This feature is only available with the --experimental-vm-modules
command\nflag enabled.
The vm.Module
class provides a low-level interface for using\nECMAScript modules in VM contexts. It is the counterpart of the vm.Script
\nclass that closely mirrors Module Records as defined in the ECMAScript\nspecification.
Unlike vm.Script
however, every vm.Module
object is bound to a context from\nits creation. Operations on vm.Module
objects are intrinsically asynchronous,\nin contrast with the synchronous nature of vm.Script
objects. The use of\n'async' functions can help with manipulating vm.Module
objects.
Using a vm.Module
object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.
This implementation lies at a lower level than the ECMAScript Module\nloader. There is also no way to interact with the Loader yet, though\nsupport is planned.
\nimport vm from 'node:vm';\n\nconst contextifiedObject = vm.createContext({\n secret: 42,\n print: console.log,\n});\n\n// Step 1\n//\n// Create a Module by constructing a new `vm.SourceTextModule` object. This\n// parses the provided source text, throwing a `SyntaxError` if anything goes\n// wrong. By default, a Module is created in the top context. But here, we\n// specify `contextifiedObject` as the context this Module belongs to.\n//\n// Here, we attempt to obtain the default export from the module \"foo\", and\n// put it into local binding \"secret\".\n\nconst bar = new vm.SourceTextModule(`\n import s from 'foo';\n s;\n print(s);\n`, { context: contextifiedObject });\n\n// Step 2\n//\n// \"Link\" the imported dependencies of this Module to it.\n//\n// The provided linking callback (the \"linker\") accepts two arguments: the\n// parent module (`bar` in this case) and the string that is the specifier of\n// the imported module. The callback is expected to return a Module that\n// corresponds to the provided specifier, with certain requirements documented\n// in `module.link()`.\n//\n// If linking has not started for the returned Module, the same linker\n// callback will be called on the returned Module.\n//\n// Even top-level Modules without dependencies must be explicitly linked. The\n// callback provided would never be called, however.\n//\n// The link() method returns a Promise that will be resolved when all the\n// Promises returned by the linker resolve.\n//\n// Note: This is a contrived example in that the linker function creates a new\n// \"foo\" module every time it is called. In a full-fledged module system, a\n// cache would probably be used to avoid duplicated modules.\n\nasync function linker(specifier, referencingModule) {\n if (specifier === 'foo') {\n return new vm.SourceTextModule(`\n // The \"secret\" variable refers to the global variable we added to\n // \"contextifiedObject\" when creating the context.\n export default secret;\n `, { context: referencingModule.context });\n\n // Using `contextifiedObject` instead of `referencingModule.context`\n // here would work as well.\n }\n throw new Error(`Unable to resolve dependency: ${specifier}`);\n}\nawait bar.link(linker);\n\n// Step 3\n//\n// Evaluate the Module. The evaluate() method returns a promise which will\n// resolve after the module has finished evaluating.\n\n// Prints 42.\nawait bar.evaluate();\n
\nconst vm = require('node:vm');\n\nconst contextifiedObject = vm.createContext({\n secret: 42,\n print: console.log,\n});\n\n(async () => {\n // Step 1\n //\n // Create a Module by constructing a new `vm.SourceTextModule` object. This\n // parses the provided source text, throwing a `SyntaxError` if anything goes\n // wrong. By default, a Module is created in the top context. But here, we\n // specify `contextifiedObject` as the context this Module belongs to.\n //\n // Here, we attempt to obtain the default export from the module \"foo\", and\n // put it into local binding \"secret\".\n\n const bar = new vm.SourceTextModule(`\n import s from 'foo';\n s;\n print(s);\n `, { context: contextifiedObject });\n\n // Step 2\n //\n // \"Link\" the imported dependencies of this Module to it.\n //\n // The provided linking callback (the \"linker\") accepts two arguments: the\n // parent module (`bar` in this case) and the string that is the specifier of\n // the imported module. The callback is expected to return a Module that\n // corresponds to the provided specifier, with certain requirements documented\n // in `module.link()`.\n //\n // If linking has not started for the returned Module, the same linker\n // callback will be called on the returned Module.\n //\n // Even top-level Modules without dependencies must be explicitly linked. The\n // callback provided would never be called, however.\n //\n // The link() method returns a Promise that will be resolved when all the\n // Promises returned by the linker resolve.\n //\n // Note: This is a contrived example in that the linker function creates a new\n // \"foo\" module every time it is called. In a full-fledged module system, a\n // cache would probably be used to avoid duplicated modules.\n\n async function linker(specifier, referencingModule) {\n if (specifier === 'foo') {\n return new vm.SourceTextModule(`\n // The \"secret\" variable refers to the global variable we added to\n // \"contextifiedObject\" when creating the context.\n export default secret;\n `, { context: referencingModule.context });\n\n // Using `contextifiedObject` instead of `referencingModule.context`\n // here would work as well.\n }\n throw new Error(`Unable to resolve dependency: ${specifier}`);\n }\n await bar.link(linker);\n\n // Step 3\n //\n // Evaluate the Module. The evaluate() method returns a promise which will\n // resolve after the module has finished evaluating.\n\n // Prints 42.\n await bar.evaluate();\n})();\n
",
"properties": [
{
"textRaw": "`dependencySpecifiers` {string\\[]}",
"type": "string\\[]",
"name": "dependencySpecifiers",
"desc": "The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.
\nCorresponds to the [[RequestedModules]]
field of Cyclic Module Records in\nthe ECMAScript specification.
If the module.status
is 'errored'
, this property contains the exception\nthrown by the module during evaluation. If the status is anything else,\naccessing this property will result in a thrown exception.
The value undefined
cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with throw undefined;
.
Corresponds to the [[EvaluationError]]
field of Cyclic Module Records\nin the ECMAScript specification.
The identifier of the current module, as set in the constructor.
" }, { "textRaw": "`namespace` {Object}", "type": "Object", "name": "namespace", "desc": "The namespace object of the module. This is only available after linking\n(module.link()
) has completed.
Corresponds to the GetModuleNamespace abstract operation in the ECMAScript\nspecification.
" }, { "textRaw": "`status` {string}", "type": "string", "name": "status", "desc": "The current status of the module. Will be one of:
\n'unlinked'
: module.link()
has not yet been called.
'linking'
: module.link()
has been called, but not all Promises returned\nby the linker function have been resolved yet.
'linked'
: The module has been linked successfully, and all of its\ndependencies are linked, but module.evaluate()
has not yet been called.
'evaluating'
: The module is being evaluated through a module.evaluate()
on\nitself or a parent module.
'evaluated'
: The module has been successfully evaluated.
'errored'
: The module has been evaluated, but an exception was thrown.
Other than 'errored'
, this status string corresponds to the specification's\nCyclic Module Record's [[Status]]
field. 'errored'
corresponds to\n'evaluated'
in the specification, but with [[EvaluationError]]
set to a\nvalue that is not undefined
.
Evaluate the module.
\nThis must be called after the module has been linked; otherwise it will reject.\nIt could be called also when the module has already been evaluated, in which\ncase it will either do nothing if the initial evaluation ended in success\n(module.status
is 'evaluated'
) or it will re-throw the exception that the\ninitial evaluation resulted in (module.status
is 'errored'
).
This method cannot be called while the module is being evaluated\n(module.status
is 'evaluating'
).
Corresponds to the Evaluate() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.
" }, { "textRaw": "`module.link(linker)`", "type": "method", "name": "link", "meta": { "changes": [ { "version": "v21.1.0", "pr-url": "https://github.com/nodejs/node/pull/50141", "description": "The option `extra.assert` is renamed to `extra.attributes`. The former name is still provided for backward compatibility." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`linker` {Function}", "name": "linker", "type": "Function", "options": [ { "textRaw": "`specifier` {string} The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```", "name": "specifier", "type": "string", "desc": "The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```" }, { "textRaw": "`referencingModule` {vm.Module} The `Module` object `link()` is called on.", "name": "referencingModule", "type": "vm.Module", "desc": "The `Module` object `link()` is called on." }, { "textRaw": "`extra` {Object}", "name": "extra", "type": "Object", "options": [ { "textRaw": "`attributes` {Object} The data from the attribute:```mjs import foo from 'foo' with { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the attribute ```Per ECMA-262, hosts are expected to trigger an error if an unsupported attribute is present.", "name": "attributes", "type": "Object", "desc": "The data from the attribute:```mjs import foo from 'foo' with { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the attribute ```Per ECMA-262, hosts are expected to trigger an error if an unsupported attribute is present." }, { "textRaw": "`assert` {Object} Alias for `extra.attributes`.", "name": "assert", "type": "Object", "desc": "Alias for `extra.attributes`." } ] }, { "textRaw": "Returns: {vm.Module|Promise}", "name": "return", "type": "vm.Module|Promise" } ] } ] } ], "desc": "Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.
\nThe function is expected to return a Module
object or a Promise
that\neventually resolves to a Module
object. The returned Module
must satisfy the\nfollowing two invariants:
Module
.status
must not be 'errored'
.If the returned Module
's status
is 'unlinked'
, this method will be\nrecursively called on the returned Module
with the same provided linker
\nfunction.
link()
returns a Promise
that will either get resolved when all linking\ninstances resolve to a valid Module
, or rejected if the linker function either\nthrows an exception or returns an invalid Module
.
The linker function roughly corresponds to the implementation-defined\nHostResolveImportedModule abstract operation in the ECMAScript\nspecification, with a few key differences:
\nThe actual HostResolveImportedModule implementation used during module\nlinking is one that returns the modules linked during linking. Since at\nthat point all modules would have been fully linked already, the\nHostResolveImportedModule implementation is fully synchronous per\nspecification.
\nCorresponds to the Link() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.
" } ] }, { "textRaw": "Class: `vm.SourceTextModule`", "type": "class", "name": "vm.SourceTextModule", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "This feature is only available with the --experimental-vm-modules
command\nflag enabled.
The vm.SourceTextModule
class provides the Source Text Module Record as\ndefined in the ECMAScript specification.
Creates a code cache that can be used with the SourceTextModule
constructor's\ncachedData
option. Returns a Buffer
. This method may be called any number\nof times before the module has been evaluated.
The code cache of the SourceTextModule
doesn't contain any JavaScript\nobservable states. The code cache is safe to be saved along side the script\nsource and used to construct new SourceTextModule
instances multiple times.
Functions in the SourceTextModule
source can be marked as lazily compiled\nand they are not compiled at construction of the SourceTextModule
. These\nfunctions are going to be compiled when they are invoked the first time. The\ncode cache serializes the metadata that V8 currently knows about the\nSourceTextModule
that it can use to speed up future compilations.
// Create an initial module\nconst module = new vm.SourceTextModule('const a = 1;');\n\n// Create cached data from this module\nconst cachedData = module.createCachedData();\n\n// Create a new module using the cached data. The code must be the same.\nconst module2 = new vm.SourceTextModule('const a = 1;', { cachedData });\n
"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} JavaScript Module code to parse",
"name": "code",
"type": "string",
"desc": "JavaScript Module code to parse"
},
{
"textRaw": "`options`",
"name": "options",
"options": [
{
"textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.",
"name": "identifier",
"type": "string",
"default": "`'vm:module(i)'` where `i` is a context-specific ascending index",
"desc": "String used in stack traces."
},
{
"textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created.",
"name": "cachedData",
"type": "Buffer|TypedArray|DataView",
"desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created."
},
{
"textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in. If no context is specified, the module is evaluated in the current execution context.",
"name": "context",
"type": "Object",
"desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in. If no context is specified, the module is evaluated in the current execution context."
},
{
"textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.",
"name": "lineOffset",
"type": "integer",
"default": "`0`",
"desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`."
},
{
"textRaw": "`columnOffset` {integer} Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.",
"name": "columnOffset",
"type": "integer",
"default": "`0`",
"desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`."
},
{
"textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.",
"name": "initializeImportMeta",
"type": "Function",
"desc": "Called during evaluation of this `Module` to initialize the `import.meta`.",
"options": [
{
"textRaw": "`meta` {import.meta}",
"name": "meta",
"type": "import.meta"
},
{
"textRaw": "`module` {vm.SourceTextModule}",
"name": "module",
"type": "vm.SourceTextModule"
}
]
},
{
"textRaw": "`importModuleDynamically` {Function} Used to specify the how the modules should be loaded during the evaluation of this module when `import()` is called. This option is part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see [Support of dynamic `import()` in compilation APIs][].",
"name": "importModuleDynamically",
"type": "Function",
"desc": "Used to specify the how the modules should be loaded during the evaluation of this module when `import()` is called. This option is part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see [Support of dynamic `import()` in compilation APIs][]."
}
]
}
],
"desc": "Creates a new SourceTextModule
instance.
Properties assigned to the import.meta
object that are objects may\nallow the module to access information outside the specified context
. Use\nvm.runInContext()
to create objects in a specific context.
import vm from 'node:vm';\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\nconst module = new vm.SourceTextModule(\n 'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n {\n initializeImportMeta(meta) {\n // Note: this object is created in the top context. As such,\n // Object.getPrototypeOf(import.meta.prop) points to the\n // Object.prototype in the top context rather than that in\n // the contextified object.\n meta.prop = {};\n },\n });\n// Since module has no dependencies, the linker function will never be called.\nawait module.link(() => {});\nawait module.evaluate();\n\n// Now, Object.prototype.secret will be equal to 42.\n//\n// To fix this problem, replace\n// meta.prop = {};\n// above with\n// meta.prop = vm.runInContext('{}', contextifiedObject);\n
\nconst vm = require('node:vm');\nconst contextifiedObject = vm.createContext({ secret: 42 });\n(async () => {\n const module = new vm.SourceTextModule(\n 'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n {\n initializeImportMeta(meta) {\n // Note: this object is created in the top context. As such,\n // Object.getPrototypeOf(import.meta.prop) points to the\n // Object.prototype in the top context rather than that in\n // the contextified object.\n meta.prop = {};\n },\n });\n // Since module has no dependencies, the linker function will never be called.\n await module.link(() => {});\n await module.evaluate();\n // Now, Object.prototype.secret will be equal to 42.\n //\n // To fix this problem, replace\n // meta.prop = {};\n // above with\n // meta.prop = vm.runInContext('{}', contextifiedObject);\n})();\n
"
}
]
},
{
"textRaw": "Class: `vm.SyntheticModule`",
"type": "class",
"name": "vm.SyntheticModule",
"meta": {
"added": [
"v13.0.0",
"v12.16.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "This feature is only available with the --experimental-vm-modules
command\nflag enabled.
The vm.SyntheticModule
class provides the Synthetic Module Record as\ndefined in the WebIDL specification. The purpose of synthetic modules is to\nprovide a generic interface for exposing non-JavaScript sources to ECMAScript\nmodule graphs.
const vm = require('node:vm');\n\nconst source = '{ \"a\": 1 }';\nconst module = new vm.SyntheticModule(['default'], function() {\n const obj = JSON.parse(source);\n this.setExport('default', obj);\n});\n\n// Use `module` in linking...\n
",
"methods": [
{
"textRaw": "`syntheticModule.setExport(name, value)`",
"type": "method",
"name": "setExport",
"meta": {
"added": [
"v13.0.0",
"v12.16.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} Name of the export to set.",
"name": "name",
"type": "string",
"desc": "Name of the export to set."
},
{
"textRaw": "`value` {any} The value to set the export to.",
"name": "value",
"type": "any",
"desc": "The value to set the export to."
}
]
}
],
"desc": "This method is used after the module is linked to set the values of exports. If\nit is called before the module is linked, an ERR_VM_MODULE_STATUS
error\nwill be thrown.
import vm from 'node:vm';\n\nconst m = new vm.SyntheticModule(['x'], () => {\n m.setExport('x', 1);\n});\n\nawait m.link(() => {});\nawait m.evaluate();\n\nassert.strictEqual(m.namespace.x, 1);\n
\nconst vm = require('node:vm');\n(async () => {\n const m = new vm.SyntheticModule(['x'], () => {\n m.setExport('x', 1);\n });\n await m.link(() => {});\n await m.evaluate();\n assert.strictEqual(m.namespace.x, 1);\n})();\n
"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`exportNames` {string\\[]} Array of names that will be exported from the module.",
"name": "exportNames",
"type": "string\\[]",
"desc": "Array of names that will be exported from the module."
},
{
"textRaw": "`evaluateCallback` {Function} Called when the module is evaluated.",
"name": "evaluateCallback",
"type": "Function",
"desc": "Called when the module is evaluated."
},
{
"textRaw": "`options`",
"name": "options",
"options": [
{
"textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.",
"name": "identifier",
"type": "string",
"default": "`'vm:module(i)'` where `i` is a context-specific ascending index",
"desc": "String used in stack traces."
},
{
"textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.",
"name": "context",
"type": "Object",
"desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in."
}
]
}
],
"desc": "Creates a new SyntheticModule
instance.
Objects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified context
. Use\nvm.runInContext()
to create objects in a specific context.
Compiles the given code into the provided context (if no context is\nsupplied, the current context is used), and returns it wrapped inside a\nfunction with the given params
.
If given a contextObject
, the vm.createContext()
method will prepare\nthat object so that it can be used in calls to\nvm.runInContext()
or script.runInContext()
. Inside such scripts,\nthe contextObject
will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.
const vm = require('node:vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\nvm.createContext(context);\n\nvm.runInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n
\nIf contextObject
is omitted (or passed explicitly as undefined
), a new,\nempty contextified object will be returned.
The vm.createContext()
method is primarily useful for creating a single\ncontext that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single context representing a\nwindow's global object, then run all <script>
tags together within that\ncontext.
The provided name
and origin
of the context are made visible through the\nInspector API.
Returns true
if the given object
object has been contextified using\nvm.createContext()
.
Measure the memory known to V8 and used by all contexts known to the\ncurrent V8 isolate, or the main context.
\noptions
<Object> Optional.\nmode
<string> Either 'summary'
or 'detailed'
. In summary mode,\nonly the memory measured for the main context will be returned. In\ndetailed mode, the memory measured for all contexts known to the\ncurrent V8 isolate will be returned.\nDefault: 'summary'
execution
<string> Either 'default'
or 'eager'
. With default\nexecution, the promise will not resolve until after the next scheduled\ngarbage collection starts, which may take a while (or never if the program\nexits before the next GC). With eager execution, the GC will be started\nright away to measure the memory.\nDefault: 'default'
ERR_CONTEXT_NOT_INITIALIZED
error.The format of the object that the returned Promise may resolve with is\nspecific to the V8 engine and may change from one version of V8 to the next.
\nThe returned result is different from the statistics returned by\nv8.getHeapSpaceStatistics()
in that vm.measureMemory()
measure the\nmemory reachable by each V8 specific contexts in the current instance of\nthe V8 engine, while the result of v8.getHeapSpaceStatistics()
measure\nthe memory occupied by each heap space in the current V8 instance.
const vm = require('node:vm');\n// Measure the memory used by the main context.\nvm.measureMemory({ mode: 'summary' })\n // This is the same as vm.measureMemory()\n .then((result) => {\n // The current format is:\n // {\n // total: {\n // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]\n // }\n // }\n console.log(result);\n });\n\nconst context = vm.createContext({ a: 1 });\nvm.measureMemory({ mode: 'detailed', execution: 'eager' })\n .then((result) => {\n // Reference the context here so that it won't be GC'ed\n // until the measurement is complete.\n console.log(context.a);\n // {\n // total: {\n // jsMemoryEstimate: 2574732,\n // jsMemoryRange: [ 2574732, 2904372 ]\n // },\n // current: {\n // jsMemoryEstimate: 2438996,\n // jsMemoryRange: [ 2438996, 2768636 ]\n // },\n // other: [\n // {\n // jsMemoryEstimate: 135736,\n // jsMemoryRange: [ 135736, 465376 ]\n // }\n // ]\n // }\n console.log(result);\n });\n
"
},
{
"textRaw": "`vm.runInContext(code, contextifiedObject[, options])`",
"type": "method",
"name": "runInContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": [
{
"version": [
"v21.7.0"
],
"pr-url": "https://github.com/nodejs/node/pull/51244",
"description": "Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."
},
{
"version": [
"v17.0.0",
"v16.12.0"
],
"pr-url": "https://github.com/nodejs/node/pull/40249",
"description": "Added support for import attributes to the `importModuleDynamically` parameter."
},
{
"version": "v6.3.0",
"pr-url": "https://github.com/nodejs/node/pull/6635",
"description": "The `breakOnSigint` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run.",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
},
{
"textRaw": "`contextifiedObject` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.",
"name": "contextifiedObject",
"type": "Object",
"desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run."
},
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.The vm.runInContext()
method compiles code
, runs it within the context of\nthe contextifiedObject
, then returns the result. Running code does not have\naccess to the local scope. The contextifiedObject
object must have been\npreviously contextified using the vm.createContext()
method.
If options
is a string, then it specifies the filename.
The following example compiles and executes different scripts using a single\ncontextified object:
\nconst vm = require('node:vm');\n\nconst contextObject = { globalVar: 1 };\nvm.createContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n vm.runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n
"
},
{
"textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`",
"type": "method",
"name": "runInNewContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": [
{
"version": [
"v21.7.0"
],
"pr-url": "https://github.com/nodejs/node/pull/51244",
"description": "Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."
},
{
"version": [
"v17.0.0",
"v16.12.0"
],
"pr-url": "https://github.com/nodejs/node/pull/40249",
"description": "Added support for import attributes to the `importModuleDynamically` parameter."
},
{
"version": "v14.6.0",
"pr-url": "https://github.com/nodejs/node/pull/34023",
"description": "The `microtaskMode` option is supported now."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/19016",
"description": "The `contextCodeGeneration` option is supported now."
},
{
"version": "v6.3.0",
"pr-url": "https://github.com/nodejs/node/pull/6635",
"description": "The `breakOnSigint` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {any} the result of the very last statement executed in the script.",
"name": "return",
"type": "any",
"desc": "the result of the very last statement executed in the script."
},
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run.",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
},
{
"textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.",
"name": "contextObject",
"type": "Object",
"desc": "An object that will be [contextified][]. If `undefined`, a new object will be created."
},
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.The vm.runInNewContext()
first contextifies the given contextObject
(or\ncreates a new contextObject
if passed as undefined
), compiles the code
,\nruns it within the created context, then returns the result. Running code\ndoes not have access to the local scope.
If options
is a string, then it specifies the filename.
The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the contextObject
.
const vm = require('node:vm');\n\nconst contextObject = {\n animal: 'cat',\n count: 2,\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n
"
},
{
"textRaw": "`vm.runInThisContext(code[, options])`",
"type": "method",
"name": "runInThisContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": [
{
"version": [
"v21.7.0"
],
"pr-url": "https://github.com/nodejs/node/pull/51244",
"description": "Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."
},
{
"version": [
"v17.0.0",
"v16.12.0"
],
"pr-url": "https://github.com/nodejs/node/pull/40249",
"description": "Added support for import attributes to the `importModuleDynamically` parameter."
},
{
"version": "v6.3.0",
"pr-url": "https://github.com/nodejs/node/pull/6635",
"description": "The `breakOnSigint` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {any} the result of the very last statement executed in the script.",
"name": "return",
"type": "any",
"desc": "the result of the very last statement executed in the script."
},
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run.",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
},
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.vm.runInThisContext()
compiles code
, runs it within the context of the\ncurrent global
and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global
object.
If options
is a string, then it specifies the filename.
The following example illustrates using both vm.runInThisContext()
and\nthe JavaScript eval()
function to run the same code:
const vm = require('node:vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = \"vm\";');\nconsole.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);\n// Prints: vmResult: 'vm', localVar: 'initial value'\n\nconst evalResult = eval('localVar = \"eval\";');\nconsole.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);\n// Prints: evalResult: 'eval', localVar: 'eval'\n
\nBecause vm.runInThisContext()
does not have access to the local scope,\nlocalVar
is unchanged. In contrast, eval()
does have access to the\nlocal scope, so the value localVar
is changed. In this way\nvm.runInThisContext()
is much like an indirect eval()
call, e.g.\n(0,eval)('code')
.
When using either script.runInThisContext()
or\nvm.runInThisContext()
, the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.
In order to run a simple web server using the node:http
module the code passed\nto the context must either call require('node:http')
on its own, or have a\nreference to the node:http
module passed to it. For instance:
'use strict';\nconst vm = require('node:vm');\n\nconst code = `\n((require) => {\n const http = require('node:http');\n\n http.createServer((request, response) => {\n response.writeHead(200, { 'Content-Type': 'text/plain' });\n response.end('Hello World\\\\n');\n }).listen(8124);\n\n console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n
\nThe require()
in the above case shares the state with the context it is\npassed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.
Returns an object containing commonly used constants for VM operations.
", "properties": [ { "textRaw": "`vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`", "name": "USE_MAIN_CONTEXT_DEFAULT_LOADER", "meta": { "added": [ "v21.7.0" ], "changes": [] }, "stability": 1, "stabilityText": ".1 - Active development", "desc": "A constant that can be used as the importModuleDynamically
option to\nvm.Script
and vm.compileFunction()
so that Node.js uses the default\nESM loader from the main context to load the requested module.
For detailed information, see\nSupport of dynamic import()
in compilation APIs.
All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the V8 Embedder's Guide:
\n\n\nIn V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.
\n
When the method vm.createContext()
is called, the contextObject
argument\n(or a newly-created object if contextObject
is undefined
) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode
run using the node:vm
module's methods with an isolated global\nenvironment within which it can operate. The process of creating the V8 Context\nand associating it with the contextObject
is what this document refers to as\n\"contextifying\" the object.
Promise
s and async function
s can schedule tasks run by the JavaScript\nengine asynchronously. By default, these tasks are run after all JavaScript\nfunctions on the current stack are done executing.\nThis allows escaping the functionality of the timeout
and\nbreakOnSigint
options.
For example, the following code executed by vm.runInNewContext()
with a\ntimeout of 5 milliseconds schedules an infinite loop to run after a promise\nresolves. The scheduled loop is never interrupted by the timeout:
const vm = require('node:vm');\n\nfunction loop() {\n console.log('entering loop');\n while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n 'Promise.resolve().then(() => loop());',\n { loop, console },\n { timeout: 5 },\n);\n// This is printed *before* 'entering loop' (!)\nconsole.log('done executing');\n
\nThis can be addressed by passing microtaskMode: 'afterEvaluate'
to the code\nthat creates the Context
:
const vm = require('node:vm');\n\nfunction loop() {\n while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n 'Promise.resolve().then(() => loop());',\n { loop, console },\n { timeout: 5, microtaskMode: 'afterEvaluate' },\n);\n
\nIn this case, the microtask scheduled through promise.then()
will be run\nbefore returning from vm.runInNewContext()
, and will be interrupted\nby the timeout
functionality. This applies only to code running in a\nvm.Context
, so e.g. vm.runInThisContext()
does not take this option.
Promise callbacks are entered into the microtask queue of the context in which\nthey were created. For example, if () => loop()
is replaced with just loop
\nin the above example, then loop
will be pushed into the global microtask\nqueue, because it is a function from the outer (main) context, and thus will\nalso be able to escape the timeout.
If asynchronous scheduling functions such as process.nextTick()
,\nqueueMicrotask()
, setTimeout()
, setImmediate()
, etc. are made available\ninside a vm.Context
, functions passed to them will be added to global queues,\nwhich are shared by all contexts. Therefore, callbacks passed to those functions\nare not controllable through the timeout either.
The following APIs support an importModuleDynamically
option to enable dynamic\nimport()
in code compiled by the vm module.
new vm.Script
vm.compileFunction()
new vm.SourceTextModule
vm.runInThisContext()
vm.runInContext()
vm.runInNewContext()
vm.createContext()
This option is still part of the experimental modules API. We do not recommend\nusing it in a production environment.
", "modules": [ { "textRaw": "When the `importModuleDynamically` option is not specified or undefined", "name": "when_the_`importmoduledynamically`_option_is_not_specified_or_undefined", "desc": "If this option is not specified, or if it's undefined
, code containing\nimport()
can still be compiled by the vm APIs, but when the compiled code is\nexecuted and it actually calls import()
, the result will reject with\nERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
.
This option is currently not supported for vm.SourceTextModule
.
With this option, when an import()
is initiated in the compiled code, Node.js\nwould use the default ESM loader from the main context to load the requested\nmodule and return it to the code being executed.
This gives access to Node.js built-in modules such as fs
or http
\nto the code being compiled. If the code is executed in a different context,\nbe aware that the objects created by modules loaded from the main context\nare still from the main context and not instanceof
built-in classes in the\nnew context.
const { Script, constants } = require('node:vm');\nconst script = new Script(\n 'import(\"node:fs\").then(({readFile}) => readFile instanceof Function)',\n { importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER });\n\n// false: URL loaded from the main context is not an instance of the Function\n// class in the new context.\nscript.runInNewContext().then(console.log);\n
\nimport { Script, constants } from 'node:vm';\n\nconst script = new Script(\n 'import(\"node:fs\").then(({readFile}) => readFile instanceof Function)',\n { importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER });\n\n// false: URL loaded from the main context is not an instance of the Function\n// class in the new context.\nscript.runInNewContext().then(console.log);\n
\nThis option also allows the script or function to load user modules:
\nimport { Script, constants } from 'node:vm';\nimport { resolve } from 'node:path';\nimport { writeFileSync } from 'node:fs';\n\n// Write test.js and test.txt to the directory where the current script\n// being run is located.\nwriteFileSync(resolve(import.meta.dirname, 'test.mjs'),\n 'export const filename = \"./test.json\";');\nwriteFileSync(resolve(import.meta.dirname, 'test.json'),\n '{\"hello\": \"world\"}');\n\n// Compile a script that loads test.mjs and then test.json\n// as if the script is placed in the same directory.\nconst script = new Script(\n `(async function() {\n const { filename } = await import('./test.mjs');\n return import(filename, { with: { type: 'json' } })\n })();`,\n {\n filename: resolve(import.meta.dirname, 'test-with-default.js'),\n importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,\n });\n\n// { default: { hello: 'world' } }\nscript.runInThisContext().then(console.log);\n
\nconst { Script, constants } = require('node:vm');\nconst { resolve } = require('node:path');\nconst { writeFileSync } = require('node:fs');\n\n// Write test.js and test.txt to the directory where the current script\n// being run is located.\nwriteFileSync(resolve(__dirname, 'test.mjs'),\n 'export const filename = \"./test.json\";');\nwriteFileSync(resolve(__dirname, 'test.json'),\n '{\"hello\": \"world\"}');\n\n// Compile a script that loads test.mjs and then test.json\n// as if the script is placed in the same directory.\nconst script = new Script(\n `(async function() {\n const { filename } = await import('./test.mjs');\n return import(filename, { with: { type: 'json' } })\n })();`,\n {\n filename: resolve(__dirname, 'test-with-default.js'),\n importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,\n });\n\n// { default: { hello: 'world' } }\nscript.runInThisContext().then(console.log);\n
\nThere are a few caveats with loading user modules using the default loader\nfrom the main context:
\nfilename
option passed\nto vm.Script
or vm.compileFunction()
. The resolution can work with a\nfilename
that's either an absolute path or a URL string. If filename
is\na string that's neither an absolute path or a URL, or if it's undefined,\nthe resolution will be relative to the current working directory\nof the process. In the case of vm.createContext()
, the resolution is always\nrelative to the current working directory since this option is only used when\nthere isn't a referrer script or module.filename
that resolves to a specific path, once the process\nmanages to load a particular module from that path, the result may be cached,\nand subsequent load of the same module from the same path would return the\nsame thing. If the filename
is a URL string, the cache would not be hit\nif it has different search parameters. For filename
s that are not URL\nstrings, there is currently no way to bypass the caching behavior.When importModuleDynamically
is a function, it will be invoked when import()
\nis called in the compiled code for users to customize how the requested module\nshould be compiled and evaluated. Currently, the Node.js instance must be\nlaunched with the --experimental-vm-modules
flag for this option to work. If\nthe flag isn't set, this callback will be ignored. If the code evaluated\nactually calls to import()
, the result will reject with\nERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG
.
The callback importModuleDynamically(specifier, referrer, importAttributes)
\nhas the following signature:
specifier
<string> specifier passed to import()
referrer
<vm.Script> | <Function> | <vm.SourceTextModule> | <Object>\nThe referrer is the compiled vm.Script
for new vm.Script
,\nvm.runInThisContext
, vm.runInContext
and vm.runInNewContext
. It's the\ncompiled Function
for vm.compileFunction
, the compiled\nvm.SourceTextModule
for new vm.SourceTextModule
, and the context Object
\nfor vm.createContext()
.importAttributes
<Object> The \"with\"
value passed to the\noptionsExpression
optional parameter, or an empty object if no value was\nprovided.vm.Module
is\nrecommended in order to take advantage of error tracking, and to avoid issues\nwith namespaces that contain then
function exports.// This script must be run with --experimental-vm-modules.\nimport { Script, SyntheticModule } from 'node:vm';\n\nconst script = new Script('import(\"foo.json\", { with: { type: \"json\" } })', {\n async importModuleDynamically(specifier, referrer, importAttributes) {\n console.log(specifier); // 'foo.json'\n console.log(referrer); // The compiled script\n console.log(importAttributes); // { type: 'json' }\n const m = new SyntheticModule(['bar'], () => { });\n await m.link(() => { });\n m.setExport('bar', { hello: 'world' });\n return m;\n },\n});\nconst result = await script.runInThisContext();\nconsole.log(result); // { bar: { hello: 'world' } }\n
\n// This script must be run with --experimental-vm-modules.\nconst { Script, SyntheticModule } = require('node:vm');\n\n(async function main() {\n const script = new Script('import(\"foo.json\", { with: { type: \"json\" } })', {\n async importModuleDynamically(specifier, referrer, importAttributes) {\n console.log(specifier); // 'foo.json'\n console.log(referrer); // The compiled script\n console.log(importAttributes); // { type: 'json' }\n const m = new SyntheticModule(['bar'], () => { });\n await m.link(() => { });\n m.setExport('bar', { hello: 'world' });\n return m;\n },\n });\n const result = await script.runInThisContext();\n console.log(result); // { bar: { hello: 'world' } }\n})();\n
",
"type": "module",
"displayName": "When `importModuleDynamically` is a function"
}
],
"type": "module",
"displayName": "Support of dynamic `import()` in compilation APIs"
}
],
"type": "module",
"displayName": "vm"
}
]
}