{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"vm","path":"/vm","type":"module","module":"vm","title":"VM (executing JavaScript)","introducedIn":"v0.10.0","sourceLink":{"path":"lib/vm.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/vm.js"},"stability":{"index":"2","description":"Stable"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `node:vm` module enables compiling and running code within V8 Virtual\nMachine contexts.\n\n<strong class=\"critical\">The `node:vm` module is not a security\nmechanism. Do not use it to run untrusted code.</strong>\n\nJavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.\n\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.\n\nOne can provide the context by [*contextifying*](#what-does-it-mean-to-contextify-an-object) 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.\n\n```mjs\nimport { createContext, runInContext } from 'node:vm';\n\nconst x = 1;\n\nconst context = { x: 2 };\ncreateContext(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.\nrunInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined\n```\n\n```cjs\nconst { createContext, runInContext } = require('node:vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\ncreateContext(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.\nrunInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined\n```","summary":"The `node:vm` module enables compiling and running code within V8 Virtual Machine contexts.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, runInContext } from 'node:vm';\n\nconst x = 1;\n\nconst context = { x: 2 };\ncreateContext(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.\nrunInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext } = require('node:vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\ncreateContext(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.\nrunInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined"}],"children":[{"kind":"class","id":"class-vmscript","name":"Script","title":"Class: `vm.Script`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"Instances of the `vm.Script` class contain precompiled scripts that can be\nexecuted in specific contexts.","summary":"Instances of the `vm.Script` class contain precompiled scripts that can be executed in specific contexts.","examples":[],"children":[{"kind":"constructor","id":"new-vmscriptcode-options","name":"Script","title":"`new vm.Script(code[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.7.0","v20.12.0"],"prUrl":"https://github.com/nodejs/node/pull/51244","commit":null,"description":"Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."},{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/40249","commit":null,"description":"Added support for import attributes to the `importModuleDynamically` parameter."},{"versions":["v10.6.0"],"prUrl":"https://github.com/nodejs/node/pull/20300","commit":null,"description":"The `produceCachedData` is deprecated in favour of `script.createCachedData()`."},{"versions":["v5.7.0"],"prUrl":"https://github.com/nodejs/node/pull/4777","commit":null,"description":"The `cachedData` and `produceCachedData` options are supported now."}],"signature":{"parameters":[{"name":"code","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The JavaScript code to compile.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object | string","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"filename","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the filename used in stack traces produced\nby this script.","default":"'evalmachine.<anonymous>'","optional":true,"rest":false,"properties":[]},{"name":"lineOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the line number offset that is displayed\nin stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"columnOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the first-line column number offset that\nis displayed in stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"cachedData","type":{"text":"Buffer | TypedArray | DataView","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30}]},"description":"Provides an optional `Buffer` or\n`TypedArray`, or `DataView` with V8's code cache data for the supplied\nsource. When supplied, the `cachedDataRejected` value will be set to\neither `true` or `false` depending on acceptance of the data by V8.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"produceCachedData","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true` and no `cachedData` is present, V8\nwill attempt to produce code cache data for `code`. Upon success, a\n`Buffer` with V8's code cache data will be produced and stored in the\n`cachedData` property of the returned `vm.Script` instance.\nThe `cachedDataProduced` value will be set to either `true` or `false`\ndepending on whether code cache data is produced successfully.\nThis option is **deprecated** in favor of `script.createCachedData()`.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"importModuleDynamically","type":{"text":"Function | vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","href":"vm.html#vmconstantsuse_main_context_default_loader","start":11,"end":55}]},"description":"Used to specify how the modules should be loaded during the evaluation\nof this script when `import()` is called. This option is part of the\nexperimental modules API. We do not recommend using it in a production\nenvironment. For detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"If `options` is a string, then it specifies the filename.\n\nCreating 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.","summary":"If `options` is a string, then it specifies the filename.","examples":[],"children":[]},{"kind":"property","id":"scriptcacheddatarejected","name":"cachedDataRejected","title":"`script.cachedDataRejected`","scope":"module","overloadOf":null,"stability":null,"added":["v5.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean | undefined","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":10,"end":19}]},"default":null,"description":"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`.","summary":"When `cachedData` is supplied to create the `vm.Script`, this value will be set to either `true` or `false` depending on acceptance of the data by V8. Otherwise the value is `undefined`.","examples":[],"children":[]},{"kind":"method","id":"scriptcreatecacheddata","name":"createCachedData","title":"`script.createCachedData()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.6.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"Buffer","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6}]},"description":""}},"description":"Creates a code cache that can be used with the `Script` constructor's\n`cachedData` option. Returns a `Buffer`. This method may be called at any\ntime and any number of times.\n\nThe 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.\n\nFunctions 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.\n\n```js\nconst 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```","summary":"Creates a code cache that can be used with the `Script` constructor's `cachedData` option. Returns a `Buffer`. This method may be called at any time and any number of times.","examples":[{"language":"js","displayName":null,"code":"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()`."}],"children":[]},{"kind":"method","id":"scriptrunincontextcontextifiedobject-options","name":"runInContext","title":"`script.runInContext(contextifiedObject[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakOnSigint` option is supported now."}],"signature":{"parameters":[{"name":"contextifiedObject","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"A [contextified](#what-does-it-mean-to-contextify-an-object) object as returned by the\n`vm.createContext()` method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"displayErrors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true`, if an [`Error`](errors.html#class-error) occurs\nwhile compiling the `code`, the line of code causing the error is attached\nto the stack trace.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to execute `code`\nbefore terminating execution. If execution is terminated, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the result of the very last statement executed in the script."}},"description":"Runs the compiled code contained by the `vm.Script` object within the given\n`contextifiedObject` and returns the result. Running code does not have access\nto local scope.\n\nThe 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.\n\n```mjs\nimport { createContext, Script } from 'node:vm';\n\nconst context = {\n  animal: 'cat',\n  count: 2,\n};\n\nconst script = new Script('count += 1; name = \"kitty\";');\n\ncreateContext(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```\n\n```cjs\nconst { createContext, Script } = require('node:vm');\n\nconst context = {\n  animal: 'cat',\n  count: 2,\n};\n\nconst script = new Script('count += 1; name = \"kitty\";');\n\ncreateContext(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```\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.","summary":"Runs the compiled code contained by the `vm.Script` object within the given `contextifiedObject` and returns the result. Running code does not have access to local scope.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, Script } from 'node:vm';\n\nconst context = {\n  animal: 'cat',\n  count: 2,\n};\n\nconst script = new Script('count += 1; name = \"kitty\";');\n\ncreateContext(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' }"},{"language":"cjs","displayName":null,"code":"const { createContext, Script } = require('node:vm');\n\nconst context = {\n  animal: 'cat',\n  count: 2,\n};\n\nconst script = new Script('count += 1; name = \"kitty\";');\n\ncreateContext(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' }"}],"children":[]},{"kind":"method","id":"scriptruninnewcontextcontextobject-options","name":"runInNewContext","title":"`script.runInNewContext([contextObject[, options]])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.8.0","v20.18.0"],"prUrl":"https://github.com/nodejs/node/pull/54394","commit":null,"description":"The `contextObject` argument now accepts `vm.constants.DONT_CONTEXTIFY`."},{"versions":["v14.6.0"],"prUrl":"https://github.com/nodejs/node/pull/34023","commit":null,"description":"The `microtaskMode` option is supported now."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/19016","commit":null,"description":"The `contextCodeGeneration` option is supported now."},{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakOnSigint` option is supported now."}],"signature":{"parameters":[{"name":"contextObject","type":{"text":"Object | vm.constants.DONT_CONTEXTIFY | undefined","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"vm.constants.DONT_CONTEXTIFY","href":"vm.html#vmconstantsdont_contextify","start":9,"end":37},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":40,"end":49}]},"description":"Either [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify) or an object that will be [contextified](#what-does-it-mean-to-contextify-an-object).\nIf `undefined`, an empty contextified object will be created for backwards compatibility.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"displayErrors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true`, if an [`Error`](errors.html#class-error) occurs\nwhile compiling the `code`, the line of code causing the error is attached\nto the stack trace.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to execute `code`\nbefore terminating execution. If execution is terminated, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"contextName","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Human-readable name of the newly created context.","default":"`'VM Context i'`, where `i` is an ascending numerical index of the created context","optional":true,"rest":false,"properties":[]},{"name":"contextOrigin","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"[Origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) corresponding to the newly\ncreated context for display purposes. The origin should be formatted like a\nURL, but with only the scheme, host, and port (if necessary), like the\nvalue of the [`url.origin`](url.html#urlorigin) property of a [`URL`](url.html#class-url) object. Most notably,\nthis string should omit the trailing slash, as that denotes a path.","default":"''","optional":true,"rest":false,"properties":[]},{"name":"contextCodeGeneration","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"strings","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to false any calls to `eval` or function\nconstructors (`Function`, `GeneratorFunction`, etc) will throw an\n`EvalError`.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"wasm","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to false any attempt to compile a WebAssembly\nmodule will throw a `WebAssembly.CompileError`.","default":"true","optional":true,"rest":false,"properties":[]}]},{"name":"microtaskMode","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"If set to `afterEvaluate`, microtasks (tasks\nscheduled through `Promise`s and `async function`s) will be run immediately\nafter the script has run. They are included in the `timeout` and\n`breakOnSigint` scopes in that case.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the result of the very last statement executed in the script."}},"description":"This method is a shortcut to `script.runInContext(vm.createContext(options), options)`.\nIt does several things at once:\n\n1. Creates a new context.\n2. If `contextObject` is an object, [contextifies](#what-does-it-mean-to-contextify-an-object) it with the new context.\n   If  `contextObject` is undefined, creates a new object and [contextifies](#what-does-it-mean-to-contextify-an-object) it.\n   If `contextObject` is [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify), don't [contextify](#what-does-it-mean-to-contextify-an-object) anything.\n3. Runs the compiled code contained by the `vm.Script` object within the created context. The code\n   does not have access to the scope in which this method is called.\n4. Returns the result.\n\nThe 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`.\n\n```mjs\nimport { constants, Script } from 'node:vm';\n\nconst script = new 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\n// This would throw if the context is created from a contextified object.\n// constants.DONT_CONTEXTIFY allows creating contexts with ordinary\n// global objects that can be frozen.\nconst freezeScript = new Script('Object.freeze(globalThis); globalThis;');\nconst frozenContext = freezeScript.runInNewContext(constants.DONT_CONTEXTIFY);\n```\n\n```cjs\nconst { constants, Script } = require('node:vm');\n\nconst script = new 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\n// This would throw if the context is created from a contextified object.\n// constants.DONT_CONTEXTIFY allows creating contexts with ordinary\n// global objects that can be frozen.\nconst freezeScript = new Script('Object.freeze(globalThis); globalThis;');\nconst frozenContext = freezeScript.runInNewContext(constants.DONT_CONTEXTIFY);\n```","summary":"This method is a shortcut to `script.runInContext(vm.createContext(options), options)`. It does several things at once:","examples":[{"language":"mjs","displayName":null,"code":"import { constants, Script } from 'node:vm';\n\nconst script = new 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\n// This would throw if the context is created from a contextified object.\n// constants.DONT_CONTEXTIFY allows creating contexts with ordinary\n// global objects that can be frozen.\nconst freezeScript = new Script('Object.freeze(globalThis); globalThis;');\nconst frozenContext = freezeScript.runInNewContext(constants.DONT_CONTEXTIFY);"},{"language":"cjs","displayName":null,"code":"const { constants, Script } = require('node:vm');\n\nconst script = new 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\n// This would throw if the context is created from a contextified object.\n// constants.DONT_CONTEXTIFY allows creating contexts with ordinary\n// global objects that can be frozen.\nconst freezeScript = new Script('Object.freeze(globalThis); globalThis;');\nconst frozenContext = freezeScript.runInNewContext(constants.DONT_CONTEXTIFY);"}],"children":[]},{"kind":"method","id":"scriptruninthiscontextoptions","name":"runInThisContext","title":"`script.runInThisContext([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakOnSigint` option is supported now."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"displayErrors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true`, if an [`Error`](errors.html#class-error) occurs\nwhile compiling the `code`, the line of code causing the error is attached\nto the stack trace.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to execute `code`\nbefore terminating execution. If execution is terminated, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the result of the very last statement executed in the script."}},"description":"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\n*does* have access to the current `global` object.\n\nThe following example compiles code that increments a `global` variable then\nexecutes that code multiple times:\n\n```mjs\nimport { Script } from 'node:vm';\n\nglobal.globalVar = 0;\n\nconst script = new 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```\n\n```cjs\nconst { Script } = require('node:vm');\n\nglobal.globalVar = 0;\n\nconst script = new 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```","summary":"Runs the compiled code contained by the `vm.Script` within the context of the current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object.","examples":[{"language":"mjs","displayName":null,"code":"import { Script } from 'node:vm';\n\nglobal.globalVar = 0;\n\nconst script = new 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"},{"language":"cjs","displayName":null,"code":"const { Script } = require('node:vm');\n\nglobal.globalVar = 0;\n\nconst script = new 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"}],"children":[]},{"kind":"property","id":"scriptsourcemapurl","name":"sourceMapURL","title":"`script.sourceMapURL`","scope":"module","overloadOf":null,"stability":null,"added":["v19.1.0","v18.13.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string | undefined","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":9,"end":18}]},"default":null,"description":"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.\n\n```mjs\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```\n\n```cjs\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```","summary":"When the script is compiled from a source that contains a source map magic comment, this property will be set to the URL of the source map.","examples":[{"language":"mjs","displayName":null,"code":"import 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"},{"language":"cjs","displayName":null,"code":"const 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"}],"children":[]}]},{"kind":"class","id":"class-vmmodule","name":"Module","title":"Class: `vm.Module`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v13.0.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"This feature is only available with the `--experimental-vm-modules` command\nflag enabled.\n\nThe `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 Record](https://tc39.es/ecma262/#sec-abstract-module-records)s as defined in the ECMAScript\nspecification.\n\nUnlike `vm.Script` however, every `vm.Module` object is bound to a context from\nits creation.\n\nUsing a `vm.Module` object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.\n\nThis implementation lies at a lower level than the [ECMAScript Module\nloader](esm.html#modules-ecmascript-modules). There is also no way to interact with the Loader yet, though\nsupport is planned.\n\n```mjs\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 rootModule = 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// Obtain the requested dependencies of a SourceTextModule by\n// `sourceTextModule.moduleRequests` and resolve them.\n//\n// Even top-level Modules without dependencies must be explicitly linked. The\n// array passed to `sourceTextModule.linkRequests(modules)` can be\n// empty, however.\n//\n// Note: This is a contrived example in that the resolveAndLinkDependencies\n// creates a new \"foo\" module every time it is called. In a full-fledged\n// module system, a cache would probably be used to avoid duplicated modules.\n\nconst moduleMap = new Map([\n  ['root', rootModule],\n]);\n\nfunction resolveAndLinkDependencies(module) {\n  const requestedModules = module.moduleRequests.map((request) => {\n    // In a full-fledged module system, the resolveAndLinkDependencies would\n    // resolve the module with the module cache key `[specifier, attributes]`.\n    // In this example, we just use the specifier as the key.\n    const specifier = request.specifier;\n\n    let requestedModule = moduleMap.get(specifier);\n    if (requestedModule === undefined) {\n      requestedModule = 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: module.context });\n      moduleMap.set(specifier, requestedModule);\n      // Resolve the dependencies of the new module as well.\n      resolveAndLinkDependencies(requestedModule);\n    }\n\n    return requestedModule;\n  });\n\n  module.linkRequests(requestedModules);\n}\n\nresolveAndLinkDependencies(rootModule);\nrootModule.instantiate();\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 rootModule.evaluate();\n```\n\n```cjs\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 rootModule = 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  // Obtain the requested dependencies of a SourceTextModule by\n  // `sourceTextModule.moduleRequests` and resolve them.\n  //\n  // Even top-level Modules without dependencies must be explicitly linked. The\n  // array passed to `sourceTextModule.linkRequests(modules)` can be\n  // empty, however.\n  //\n  // Note: This is a contrived example in that the resolveAndLinkDependencies\n  // creates a new \"foo\" module every time it is called. In a full-fledged\n  // module system, a cache would probably be used to avoid duplicated modules.\n\n  const moduleMap = new Map([\n    ['root', rootModule],\n  ]);\n\n  function resolveAndLinkDependencies(module) {\n    const requestedModules = module.moduleRequests.map((request) => {\n      // In a full-fledged module system, the resolveAndLinkDependencies would\n      // resolve the module with the module cache key `[specifier, attributes]`.\n      // In this example, we just use the specifier as the key.\n      const specifier = request.specifier;\n\n      let requestedModule = moduleMap.get(specifier);\n      if (requestedModule === undefined) {\n        requestedModule = 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: module.context });\n        moduleMap.set(specifier, requestedModule);\n        // Resolve the dependencies of the new module as well.\n        resolveAndLinkDependencies(requestedModule);\n      }\n\n      return requestedModule;\n    });\n\n    module.linkRequests(requestedModules);\n  }\n\n  resolveAndLinkDependencies(rootModule);\n  rootModule.instantiate();\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 rootModule.evaluate();\n})();\n```","summary":"This feature is only available with the `--experimental-vm-modules` command flag enabled.","examples":[{"language":"mjs","displayName":null,"code":"import 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 rootModule = 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// Obtain the requested dependencies of a SourceTextModule by\n// `sourceTextModule.moduleRequests` and resolve them.\n//\n// Even top-level Modules without dependencies must be explicitly linked. The\n// array passed to `sourceTextModule.linkRequests(modules)` can be\n// empty, however.\n//\n// Note: This is a contrived example in that the resolveAndLinkDependencies\n// creates a new \"foo\" module every time it is called. In a full-fledged\n// module system, a cache would probably be used to avoid duplicated modules.\n\nconst moduleMap = new Map([\n  ['root', rootModule],\n]);\n\nfunction resolveAndLinkDependencies(module) {\n  const requestedModules = module.moduleRequests.map((request) => {\n    // In a full-fledged module system, the resolveAndLinkDependencies would\n    // resolve the module with the module cache key `[specifier, attributes]`.\n    // In this example, we just use the specifier as the key.\n    const specifier = request.specifier;\n\n    let requestedModule = moduleMap.get(specifier);\n    if (requestedModule === undefined) {\n      requestedModule = 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: module.context });\n      moduleMap.set(specifier, requestedModule);\n      // Resolve the dependencies of the new module as well.\n      resolveAndLinkDependencies(requestedModule);\n    }\n\n    return requestedModule;\n  });\n\n  module.linkRequests(requestedModules);\n}\n\nresolveAndLinkDependencies(rootModule);\nrootModule.instantiate();\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 rootModule.evaluate();"},{"language":"cjs","displayName":null,"code":"const 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 rootModule = 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  // Obtain the requested dependencies of a SourceTextModule by\n  // `sourceTextModule.moduleRequests` and resolve them.\n  //\n  // Even top-level Modules without dependencies must be explicitly linked. The\n  // array passed to `sourceTextModule.linkRequests(modules)` can be\n  // empty, however.\n  //\n  // Note: This is a contrived example in that the resolveAndLinkDependencies\n  // creates a new \"foo\" module every time it is called. In a full-fledged\n  // module system, a cache would probably be used to avoid duplicated modules.\n\n  const moduleMap = new Map([\n    ['root', rootModule],\n  ]);\n\n  function resolveAndLinkDependencies(module) {\n    const requestedModules = module.moduleRequests.map((request) => {\n      // In a full-fledged module system, the resolveAndLinkDependencies would\n      // resolve the module with the module cache key `[specifier, attributes]`.\n      // In this example, we just use the specifier as the key.\n      const specifier = request.specifier;\n\n      let requestedModule = moduleMap.get(specifier);\n      if (requestedModule === undefined) {\n        requestedModule = 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: module.context });\n        moduleMap.set(specifier, requestedModule);\n        // Resolve the dependencies of the new module as well.\n        resolveAndLinkDependencies(requestedModule);\n      }\n\n      return requestedModule;\n    });\n\n    module.linkRequests(requestedModules);\n  }\n\n  resolveAndLinkDependencies(rootModule);\n  rootModule.instantiate();\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 rootModule.evaluate();\n})();"}],"children":[{"kind":"property","id":"moduleerror","name":"error","title":"`module.error`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"default":null,"description":"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.\n\nThe value `undefined` cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with `throw undefined;`.\n\nCorresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)s\nin the ECMAScript specification.","summary":"If the `module.status` is `'errored'`, this property contains the exception thrown by the module during evaluation. If the status is anything else, accessing this property will result in a thrown exception.","examples":[],"children":[]},{"kind":"method","id":"moduleevaluateoptions","name":"evaluate","title":"`module.evaluate([options])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to evaluate\nbefore terminating execution. If execution is interrupted, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"Fulfills with `undefined` upon success."}},"description":"Evaluate the module and its dependencies. Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of\n[Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)s in the ECMAScript specification.\n\nIf the module is a `vm.SourceTextModule`, `evaluate()` must be called after the module has been instantiated;\notherwise `evaluate()` will return a rejected promise.\n\nFor a `vm.SourceTextModule`, the promise returned by `evaluate()` may be fulfilled either\nsynchronously or asynchronously:\n\n1. If the `vm.SourceTextModule` has no top-level `await` in itself or any of its dependencies, the promise will be\n   fulfilled *synchronously* after the module and all its dependencies have been evaluated.\n   1. If the evaluation succeeds, the promise will be *synchronously* resolved to `undefined`.\n   2. If the evaluation results in an exception, the promise will be *synchronously* rejected with the exception\n      that causes the evaluation to fail, which is the same as `module.error`.\n2. If the `vm.SourceTextModule` has top-level `await` in itself or any of its dependencies, the promise will be\n   fulfilled *asynchronously* after the module and all its dependencies have been evaluated.\n   1. If the evaluation succeeds, the promise will be *asynchronously* resolved to `undefined`.\n   2. If the evaluation results in an exception, the promise will be *asynchronously* rejected with the exception\n      that causes the evaluation to fail.\n\nIf the module is a `vm.SyntheticModule`, `evaluate()` always returns a promise that fulfills synchronously, see\nthe specification of [Evaluate() of a Synthetic Module Record](https://tc39.es/ecma262/#sec-smr-Evaluate):\n\n1. If the `evaluateCallback` passed to its constructor throws an exception synchronously, `evaluate()` returns\n   a promise that will be synchronously rejected with that exception.\n2. If the `evaluateCallback` does not throw an exception, `evaluate()` returns a promise that will be\n   synchronously resolved to `undefined`.\n\nThe `evaluateCallback` of a `vm.SyntheticModule` is executed synchronously within the `evaluate()` call, and its\nreturn value is discarded. This means if `evaluateCallback` is an asynchronous function, the promise returned by\n`evaluate()` will not reflect its asynchronous behavior, and any rejections from an asynchronous\n`evaluateCallback` will be lost.\n\n`evaluate()` could also be called again after the module has already been evaluated, in which case:\n\n1. If the initial evaluation ended in success (`module.status` is `'evaluated'`), it will do nothing\n   and return a promise that resolves to `undefined`.\n2. If the initial evaluation resulted in an exception (`module.status` is `'errored'`), it will re-reject\n   the exception that the initial evaluation resulted in.\n\nThis method cannot be called while the module is being evaluated (`module.status` is `'evaluating'`).","summary":"Evaluate the module and its dependencies. Corresponds to the Evaluate() concrete method field of Cyclic Module Records in the ECMAScript specification.","examples":[],"children":[]},{"kind":"property","id":"moduleidentifier","name":"identifier","title":"`module.identifier`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The identifier of the current module, as set in the constructor.","summary":"The identifier of the current module, as set in the constructor.","examples":[],"children":[]},{"kind":"method","id":"modulelinklinker","name":"link","title":"`module.link(linker)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.1.0","v20.10.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/50141","commit":null,"description":"The option `extra.assert` is renamed to `extra.attributes`. The former name is still provided for backward compatibility."}],"signature":{"parameters":[{"name":"linker","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"specifier","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The specifier of the requested module:\n\n```mjs\nimport foo from 'foo';\n//              ^^^^^ the module specifier\n```","default":null,"optional":false,"rest":false,"properties":[]},{"name":"referencingModule","type":{"text":"vm.Module","links":[{"name":"vm.Module","href":"vm.html#class-vmmodule","start":0,"end":9}]},"description":"The `Module` object `link()` is called on.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"extra","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"attributes","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The data from the attribute:\n\n```mjs\nimport foo from 'foo' with { name: 'value' };\n//                         ^^^^^^^^^^^^^^^^^ the attribute\n```\n\nPer ECMA-262, hosts are expected to trigger an error if an\nunsupported attribute is present.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"assert","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Alias for `extra.attributes`.","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"","type":{"text":"vm.Module | Promise","links":[{"name":"vm.Module","href":"vm.html#class-vmmodule","start":0,"end":9},{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":12,"end":19}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.\n\nUse [`sourceTextModule.linkRequests(modules)`](#sourcetextmodulelinkrequestsmodules) and\n[`sourceTextModule.instantiate()`](#sourcetextmoduleinstantiate) to link modules either synchronously or\nasynchronously.\n\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:\n\n* It must belong to the same context as the parent `Module`.\n* Its `status` must not be `'errored'`.\n\nIf the returned `Module`'s `status` is `'unlinked'`, this method will be\nrecursively called on the returned `Module` with the same provided `linker`\nfunction.\n\n`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`.\n\nThe linker function roughly corresponds to the implementation-defined\n[HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the ECMAScript\nspecification, with a few key differences:\n\n* The linker function is allowed to be asynchronous while\n  [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous.\n\nThe actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-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\n[HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per\nspecification.\n\nCorresponds to the [Link() concrete method](https://tc39.es/ecma262/#sec-moduledeclarationlinking) field of [Cyclic Module\nRecord](https://tc39.es/ecma262/#sec-cyclic-module-records)s in the ECMAScript specification.","summary":"Link module dependencies. This method must be called before evaluation, and can only be called once per module.","examples":[],"children":[]},{"kind":"property","id":"modulenamespace","name":"namespace","title":"`module.namespace`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"The namespace object of the module. This is only available after linking\n(`module.link()`) has completed.\n\nCorresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript\nspecification.","summary":"The namespace object of the module. This is only available after linking (`module.link()`) has completed.","examples":[],"children":[]},{"kind":"property","id":"modulestatus","name":"status","title":"`module.status`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The current status of the module. Will be one of:\n\n* `'unlinked'`: `module.link()` has not yet been called.\n\n* `'linking'`: `module.link()` has been called, but not all Promises returned\n  by the linker function have been resolved yet.\n\n* `'linked'`: The module has been linked successfully, and all of its\n  dependencies are linked, but `module.evaluate()` has not yet been called.\n\n* `'evaluating'`: The module is being evaluated through a `module.evaluate()` on\n  itself or a parent module.\n\n* `'evaluated'`: The module has been successfully evaluated.\n\n* `'errored'`: The module has been evaluated, but an exception was thrown.\n\nOther than `'errored'`, this status string corresponds to the specification's\n[Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)'s `[[Status]]` field. `'errored'` corresponds to\n`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a\nvalue that is not `undefined`.","summary":"The current status of the module. Will be one of:","examples":[],"children":[]}]},{"kind":"class","id":"class-vmsourcetextmodule","name":"SourceTextModule","title":"Class: `vm.SourceTextModule`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v9.6.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":{"text":"vm.Module","links":[{"name":"vm.Module","href":"vm.html#class-vmmodule","start":0,"end":9}]},"description":"This feature is only available with the `--experimental-vm-modules` command\nflag enabled.\n\nThe `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as\ndefined in the ECMAScript specification.","summary":"This feature is only available with the `--experimental-vm-modules` command flag enabled.","examples":[],"children":[{"kind":"constructor","id":"new-vmsourcetextmodulecode-options","name":"SourceTextModule","title":"`new vm.SourceTextModule(code[, options])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/40249","commit":null,"description":"Added support for import attributes to the `importModuleDynamically` parameter."}],"signature":{"parameters":[{"name":"code","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"JavaScript Module code to parse","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":null,"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"identifier","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"String used in stack traces.","default":"`'vm:module(i)'` where `i` is a context-specific ascending index","optional":true,"rest":false,"properties":[]},{"name":"cachedData","type":{"text":"Buffer | TypedArray | DataView","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30}]},"description":"Provides an optional `Buffer` or\n`TypedArray`, or `DataView` with V8's code cache data for the supplied\nsource. The `code` must be the same as the module from which this\n`cachedData` was created.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"context","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The [contextified](#what-does-it-mean-to-contextify-an-object) object as returned by the\n`vm.createContext()` method, to compile and evaluate this `Module` in.\nIf no context is specified, the module is evaluated in the current\nexecution context.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"lineOffset","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the line number offset that is displayed\nin stack traces produced by this `Module`.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"columnOffset","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the first-line column number offset that\nis displayed in stack traces produced by this `Module`.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"initializeImportMeta","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Called during evaluation of this `Module`\nto initialize the `import.meta`.","default":null,"optional":false,"rest":false,"properties":[{"name":"meta","type":{"text":"import.meta","links":[{"name":"import.meta","href":"esm.html#importmeta","start":0,"end":11}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"module","type":{"text":"vm.SourceTextModule","links":[{"name":"vm.SourceTextModule","href":"vm.html#class-vmsourcetextmodule","start":0,"end":19}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"importModuleDynamically","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Used to specify the\nhow the modules should be loaded during the evaluation of this module\nwhen `import()` is called. This option is part of the experimental\nmodules API. We do not recommend using it in a production environment.\nFor detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"Creates a new `SourceTextModule` instance.\n\nProperties assigned to the `import.meta` object that are objects may\nallow the module to access information outside the specified `context`. Use\n`vm.runInContext()` to create objects in a specific context.\n\n```mjs\nimport 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    context: contextifiedObject,\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// The module has an empty `moduleRequests` array.\nmodule.linkRequests([]);\nmodule.instantiate();\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```\n\n```cjs\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      context: contextifiedObject,\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  // The module has an empty `moduleRequests` array.\n  module.linkRequests([]);\n  module.instantiate();\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```","summary":"Creates a new `SourceTextModule` instance.","examples":[{"language":"mjs","displayName":null,"code":"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    context: contextifiedObject,\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// The module has an empty `moduleRequests` array.\nmodule.linkRequests([]);\nmodule.instantiate();\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);"},{"language":"cjs","displayName":null,"code":"const 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      context: contextifiedObject,\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  // The module has an empty `moduleRequests` array.\n  module.linkRequests([]);\n  module.instantiate();\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})();"}],"children":[]},{"kind":"method","id":"sourcetextmodulecreatecacheddata","name":"createCachedData","title":"`sourceTextModule.createCachedData()`","scope":"module","overloadOf":null,"stability":null,"added":["v13.7.0","v12.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"Buffer","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6}]},"description":""}},"description":"Creates a code cache that can be used with the `SourceTextModule` constructor's\n`cachedData` option. Returns a `Buffer`. This method may be called any number\nof times before the module has been evaluated.\n\nThe 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.\n\nFunctions 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\n`SourceTextModule` that it can use to speed up future compilations.\n\n```js\n// 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```","summary":"Creates a code cache that can be used with the `SourceTextModule` constructor's `cachedData` option. Returns a `Buffer`. This method may be called any number of times before the module has been evaluated.","examples":[{"language":"js","displayName":null,"code":"// 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 });"}],"children":[]},{"kind":"property","id":"sourcetextmoduledependencyspecifiers","name":"dependencySpecifiers","title":"`sourceTextModule.dependencySpecifiers`","scope":"module","overloadOf":null,"stability":{"index":"0","description":"Deprecated: Use [`sourceTextModule.moduleRequests`](#sourcetextmodulemodulerequests) instead."},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.4.0","v22.20.0"],"prUrl":"https://github.com/nodejs/node/pull/20300","commit":null,"description":"This is deprecated in favour of `sourceTextModule.moduleRequests`."}],"type":{"text":"string[]","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.\n\nCorresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)s in\nthe ECMAScript specification.","summary":"The specifiers of all dependencies of this module. The returned array is frozen to disallow any changes to it.","examples":[],"children":[]},{"kind":"method","id":"sourcetextmodulehasasyncgraph","name":"hasAsyncGraph","title":"`sourceTextModule.hasAsyncGraph()`","scope":"module","overloadOf":null,"stability":null,"added":["v24.9.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"Iterates over the dependency graph and returns `true` if any module in its\ndependencies or this module itself contains top-level `await` expressions,\notherwise returns `false`.\n\nThe search may be slow if the graph is big enough.\n\nThis requires the module to be instantiated first. If the module is not\ninstantiated yet, an error will be thrown.","summary":"Iterates over the dependency graph and returns `true` if any module in its dependencies or this module itself contains top-level `await` expressions, otherwise returns `false`.","examples":[],"children":[]},{"kind":"method","id":"sourcetextmodulehastoplevelawait","name":"hasTopLevelAwait","title":"`sourceTextModule.hasTopLevelAwait()`","scope":"module","overloadOf":null,"stability":null,"added":["v24.9.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"Returns whether the module itself contains any top-level `await` expressions.\n\nThis corresponds to the field `[[HasTLA]]` in [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) in the\nECMAScript specification.","summary":"Returns whether the module itself contains any top-level `await` expressions.","examples":[],"children":[]},{"kind":"method","id":"sourcetextmoduleinstantiate","name":"instantiate","title":"`sourceTextModule.instantiate()`","scope":"module","overloadOf":null,"stability":null,"added":["v24.8.0","v22.21.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"undefined","links":[{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":0,"end":9}]},"description":""}},"description":"Instantiate the module with the linked requested modules.\n\nThis resolves the imported bindings of the module, including re-exported\nbinding names. When there are any bindings that cannot be resolved,\nan error would be thrown synchronously.\n\nIf the requested modules include cyclic dependencies, the\n[`sourceTextModule.linkRequests(modules)`](#sourcetextmodulelinkrequestsmodules) method must be called on all\nmodules in the cycle before calling this method.","summary":"Instantiate the module with the linked requested modules.","examples":[],"children":[]},{"kind":"method","id":"sourcetextmodulelinkrequestsmodules","name":"linkRequests","title":"`sourceTextModule.linkRequests(modules)`","scope":"module","overloadOf":null,"stability":null,"added":["v24.8.0","v22.21.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"modules","type":{"text":"vm.Module[]","links":[{"name":"vm.Module","href":"vm.html#class-vmmodule","start":0,"end":9}]},"description":"Array of `vm.Module` objects that this module depends on.\nThe order of the modules in the array is the order of\n[`sourceTextModule.moduleRequests`](#sourcetextmodulemodulerequests).","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"undefined","links":[{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":0,"end":9}]},"description":""}},"description":"Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.\n\nThe order of the module instances in the `modules` array should correspond to the order of\n[`sourceTextModule.moduleRequests`](#sourcetextmodulemodulerequests) being resolved. If two module requests have the same\nspecifier and import attributes, they must be resolved with the same module instance or an\n`ERR_MODULE_LINK_MISMATCH` would be thrown. For example, when linking requests for this\nmodule:\n\n```mjs\nimport foo from 'foo';\nimport source Foo from 'foo';\n```\n\nThe `modules` array must contain two references to the same instance, because the two\nmodule requests are identical but in two phases.\n\nIf the module has no dependencies, the `modules` array can be empty.\n\nUsers can use `sourceTextModule.moduleRequests` to implement the host-defined\n[HostLoadImportedModule](https://tc39.es/ecma262/#sec-HostLoadImportedModule) abstract operation in the ECMAScript specification,\nand using `sourceTextModule.linkRequests()` to invoke specification defined\n[FinishLoadingImportedModule](https://tc39.es/ecma262/#sec-FinishLoadingImportedModule), on the module with all dependencies in a batch.\n\nIt's up to the creator of the `SourceTextModule` to determine if the resolution\nof the dependencies is synchronous or asynchronous.\n\nAfter each module in the `modules` array is linked, call\n[`sourceTextModule.instantiate()`](#sourcetextmoduleinstantiate).","summary":"Link module dependencies. This method must be called before evaluation, and can only be called once per module.","examples":[{"language":"mjs","displayName":null,"code":"import foo from 'foo';\nimport source Foo from 'foo';"}],"children":[]},{"kind":"property","id":"sourcetextmodulemodulerequests","name":"moduleRequests","title":"`sourceTextModule.moduleRequests`","scope":"module","overloadOf":null,"stability":null,"added":["v24.4.0","v22.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"ModuleRequest[]","links":[{"name":"ModuleRequest","href":"vm.html#type-modulerequest","start":0,"end":13}]},"default":null,"description":"Dependencies of this module.\n\nThe requested import dependencies of this module. The returned array is frozen\nto disallow any changes to it.\n\nFor example, given a source text:\n\n```mjs\nimport foo from 'foo';\nimport fooAlias from 'foo';\nimport bar from './bar.js';\nimport withAttrs from '../with-attrs.ts' with { arbitraryAttr: 'attr-val' };\nimport source Module from 'wasm-mod.wasm';\n```\n\nThe value of the `sourceTextModule.moduleRequests` will be:\n\n```js\n[\n  {\n    specifier: 'foo',\n    attributes: {},\n    phase: 'evaluation',\n  },\n  {\n    specifier: 'foo',\n    attributes: {},\n    phase: 'evaluation',\n  },\n  {\n    specifier: './bar.js',\n    attributes: {},\n    phase: 'evaluation',\n  },\n  {\n    specifier: '../with-attrs.ts',\n    attributes: { arbitraryAttr: 'attr-val' },\n    phase: 'evaluation',\n  },\n  {\n    specifier: 'wasm-mod.wasm',\n    attributes: {},\n    phase: 'source',\n  },\n];\n```","summary":"The requested import dependencies of this module. The returned array is frozen to disallow any changes to it.","examples":[{"language":"mjs","displayName":null,"code":"import foo from 'foo';\nimport fooAlias from 'foo';\nimport bar from './bar.js';\nimport withAttrs from '../with-attrs.ts' with { arbitraryAttr: 'attr-val' };\nimport source Module from 'wasm-mod.wasm';"},{"language":"js","displayName":null,"code":"[\n  {\n    specifier: 'foo',\n    attributes: {},\n    phase: 'evaluation',\n  },\n  {\n    specifier: 'foo',\n    attributes: {},\n    phase: 'evaluation',\n  },\n  {\n    specifier: './bar.js',\n    attributes: {},\n    phase: 'evaluation',\n  },\n  {\n    specifier: '../with-attrs.ts',\n    attributes: { arbitraryAttr: 'attr-val' },\n    phase: 'evaluation',\n  },\n  {\n    specifier: 'wasm-mod.wasm',\n    attributes: {},\n    phase: 'source',\n  },\n];"}],"children":[]}]},{"kind":"class","id":"class-vmsyntheticmodule","name":"SyntheticModule","title":"Class: `vm.SyntheticModule`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v13.0.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":{"text":"vm.Module","links":[{"name":"vm.Module","href":"vm.html#class-vmmodule","start":0,"end":9}]},"description":"This feature is only available with the `--experimental-vm-modules` command\nflag enabled.\n\nThe `vm.SyntheticModule` class provides the [Synthetic Module Record](https://tc39.es/ecma262/#sec-synthetic-module-records) 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.\n\n```mjs\nimport { SyntheticModule } from 'node:vm';\n\nconst source = '{ \"a\": 1 }';\nconst syntheticModule = new SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `syntheticModule` in linking\n(async () => {\n  await syntheticModule.link(() => {});\n  await syntheticModule.evaluate();\n\n  console.log('Default export:', syntheticModule.namespace.default);\n})();\n```\n\n```cjs\nconst { SyntheticModule } = require('node:vm');\n\nconst source = '{ \"a\": 1 }';\nconst syntheticModule = new SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `syntheticModule` in linking\n(async () => {\n  await syntheticModule.link(() => {});\n  await syntheticModule.evaluate();\n\n  console.log('Default export:', syntheticModule.namespace.default);\n})();\n```","summary":"This feature is only available with the `--experimental-vm-modules` command flag enabled.","examples":[{"language":"mjs","displayName":null,"code":"import { SyntheticModule } from 'node:vm';\n\nconst source = '{ \"a\": 1 }';\nconst syntheticModule = new SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `syntheticModule` in linking\n(async () => {\n  await syntheticModule.link(() => {});\n  await syntheticModule.evaluate();\n\n  console.log('Default export:', syntheticModule.namespace.default);\n})();"},{"language":"cjs","displayName":null,"code":"const { SyntheticModule } = require('node:vm');\n\nconst source = '{ \"a\": 1 }';\nconst syntheticModule = new SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `syntheticModule` in linking\n(async () => {\n  await syntheticModule.link(() => {});\n  await syntheticModule.evaluate();\n\n  console.log('Default export:', syntheticModule.namespace.default);\n})();"}],"children":[{"kind":"constructor","id":"new-vmsyntheticmoduleexportnames-evaluatecallback-options","name":"SyntheticModule","title":"`new vm.SyntheticModule(exportNames, evaluateCallback[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v13.0.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"exportNames","type":{"text":"string[]","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Array of names that will be exported from the\nmodule.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"evaluateCallback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Called when the module is evaluated.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":null,"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"identifier","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"String used in stack traces.","default":"`'vm:module(i)'` where `i` is a context-specific ascending index","optional":true,"rest":false,"properties":[]},{"name":"context","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The [contextified](#what-does-it-mean-to-contextify-an-object) object as returned by the\n`vm.createContext()` method, to compile and evaluate this `Module` in.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"Creates a new `SyntheticModule` instance.\n\nObjects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified `context`. Use\n`vm.runInContext()` to create objects in a specific context.","summary":"Creates a new `SyntheticModule` instance.","examples":[],"children":[]},{"kind":"method","id":"syntheticmodulesetexportname-value","name":"setExport","title":"`syntheticModule.setExport(name, value)`","scope":"module","overloadOf":null,"stability":null,"added":["v13.0.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.8.0","v22.21.0"],"prUrl":"https://github.com/nodejs/node/pull/59000","commit":null,"description":"No longer need to call `syntheticModule.link()` before calling this method."}],"signature":{"parameters":[{"name":"name","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Name of the export to set.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"The value to set the export to.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"This method sets the module export binding slots with the given value.\n\n```mjs\nimport vm from 'node:vm';\n\nconst m = new vm.SyntheticModule(['x'], () => {\n  m.setExport('x', 1);\n});\n\nawait m.evaluate();\n\nassert.strictEqual(m.namespace.x, 1);\n```\n\n```cjs\nconst vm = require('node:vm');\n(async () => {\n  const m = new vm.SyntheticModule(['x'], () => {\n    m.setExport('x', 1);\n  });\n  await m.evaluate();\n  assert.strictEqual(m.namespace.x, 1);\n})();\n```","summary":"This method sets the module export binding slots with the given value.","examples":[{"language":"mjs","displayName":null,"code":"import vm from 'node:vm';\n\nconst m = new vm.SyntheticModule(['x'], () => {\n  m.setExport('x', 1);\n});\n\nawait m.evaluate();\n\nassert.strictEqual(m.namespace.x, 1);"},{"language":"cjs","displayName":null,"code":"const vm = require('node:vm');\n(async () => {\n  const m = new vm.SyntheticModule(['x'], () => {\n    m.setExport('x', 1);\n  });\n  await m.evaluate();\n  assert.strictEqual(m.namespace.x, 1);\n})();"}],"children":[]}]},{"kind":"section","id":"type-modulerequest","name":"Type: ModuleRequest","title":"Type: `ModuleRequest`","scope":"module","overloadOf":null,"stability":null,"added":["v24.4.0","v22.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"* Type: {Object}\n  * `specifier` {string} The specifier of the requested module.\n  * `attributes` {Object} The `\"with\"` value passed to the\n    [WithClause](https://tc39.es/ecma262/#prod-WithClause) in a [ImportDeclaration](https://tc39.es/ecma262/#prod-ImportDeclaration), or an empty object if no value was\n    provided.\n  * `phase` {string} The phase of the requested module (`\"source\"` or `\"evaluation\"`).\n\nA `ModuleRequest` represents the request to import a module with given import attributes and phase.","summary":"A `ModuleRequest` represents the request to import a module with given import attributes and phase.","examples":[],"children":[]},{"kind":"method","id":"vmcompilefunctioncode-params-options","name":"compileFunction","title":"`vm.compileFunction(code[, params[, options]])`","scope":"module","overloadOf":null,"stability":null,"added":["v10.10.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.7.0","v20.12.0"],"prUrl":"https://github.com/nodejs/node/pull/51244","commit":null,"description":"Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."},{"versions":["v19.6.0","v18.15.0"],"prUrl":"https://github.com/nodejs/node/pull/46320","commit":null,"description":"The return value now includes `cachedDataRejected` with the same semantics as the `vm.Script` version if the `cachedData` option was passed."},{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/40249","commit":null,"description":"Added support for import attributes to the `importModuleDynamically` parameter."},{"versions":["v15.9.0"],"prUrl":"https://github.com/nodejs/node/pull/35431","commit":null,"description":"Added `importModuleDynamically` option again."},{"versions":["v14.3.0"],"prUrl":"https://github.com/nodejs/node/pull/33364","commit":null,"description":"Removal of `importModuleDynamically` due to compatibility issues."},{"versions":["v14.1.0","v13.14.0"],"prUrl":"https://github.com/nodejs/node/pull/32985","commit":null,"description":"The `importModuleDynamically` option is now supported."}],"signature":{"parameters":[{"name":"code","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The body of the function to compile.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"params","type":{"text":"string[]","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"An array of strings containing all parameters for the\nfunction.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"filename","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the filename used in stack traces produced\nby this script.","default":"''","optional":true,"rest":false,"properties":[]},{"name":"lineOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the line number offset that is displayed\nin stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"columnOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the first-line column number offset that\nis displayed in stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"cachedData","type":{"text":"Buffer | TypedArray | DataView","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30}]},"description":"Provides an optional `Buffer` or\n`TypedArray`, or `DataView` with V8's code cache data for the supplied\nsource. This must be produced by a prior call to [`vm.compileFunction()`](#vmcompilefunctioncode-params-options)\nwith the same `code` and `params`.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"produceCachedData","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Specifies whether to produce new cache data.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"parsingContext","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The [contextified](#what-does-it-mean-to-contextify-an-object) object in which the said\nfunction should be compiled in.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"contextExtensions","type":{"text":"Object[]","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"An array containing a collection of context\nextensions (objects wrapping the current scope) to be applied while\ncompiling.","default":"[]","optional":true,"rest":false,"properties":[]},{"name":"importModuleDynamically","type":{"text":"Function | vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","href":"vm.html#vmconstantsuse_main_context_default_loader","start":11,"end":55}]},"description":"Used to specify the how the modules should be loaded during the evaluation of\nthis function when `import()` is called. This option is part of the\nexperimental modules API. We do not recommend using it in a production\nenvironment. For detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":""}},"description":"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`.","summary":"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`.","examples":[],"children":[]},{"kind":"property","id":"vmconstants","name":"constants","title":"`vm.constants`","scope":"module","overloadOf":null,"stability":null,"added":["v21.7.0","v20.12.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"Returns an object containing commonly used constants for VM operations.","summary":"Returns an object containing commonly used constants for VM operations.","examples":[],"children":[{"kind":"property","id":"vmconstantsuse_main_context_default_loader","name":"USE_MAIN_CONTEXT_DEFAULT_LOADER","title":"`vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`","scope":"module","overloadOf":null,"stability":{"index":"1.1","description":"Active development"},"added":["v21.7.0","v20.12.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"A constant that can be used as the `importModuleDynamically` option to\n`vm.Script` and `vm.compileFunction()` so that Node.js uses the default\nESM loader from the main context to load the requested module.\n\nFor detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","summary":"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.","examples":[],"children":[]}]},{"kind":"method","id":"vmcreatecontextcontextobject-options","name":"createContext","title":"`vm.createContext([contextObject[, options]])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.8.0","v20.18.0"],"prUrl":"https://github.com/nodejs/node/pull/54394","commit":null,"description":"The `contextObject` argument now accepts `vm.constants.DONT_CONTEXTIFY`."},{"versions":["v21.7.0","v20.12.0"],"prUrl":"https://github.com/nodejs/node/pull/51244","commit":null,"description":"Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."},{"versions":["v21.2.0","v20.11.0"],"prUrl":"https://github.com/nodejs/node/pull/50360","commit":null,"description":"The `importModuleDynamically` option is supported now."},{"versions":["v14.6.0"],"prUrl":"https://github.com/nodejs/node/pull/34023","commit":null,"description":"The `microtaskMode` option is supported now."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/19398","commit":null,"description":"The first argument can no longer be a function."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/19016","commit":null,"description":"The `codeGeneration` option is supported now."}],"signature":{"parameters":[{"name":"contextObject","type":{"text":"Object | vm.constants.DONT_CONTEXTIFY | undefined","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"vm.constants.DONT_CONTEXTIFY","href":"vm.html#vmconstantsdont_contextify","start":9,"end":37},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":40,"end":49}]},"description":"Either [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify) or an object that will be [contextified](#what-does-it-mean-to-contextify-an-object).\nIf `undefined`, an empty contextified object will be created for backwards compatibility.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"name","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Human-readable name of the newly created context.","default":"`'VM Context i'`, where `i` is an ascending numerical index of the created context","optional":true,"rest":false,"properties":[]},{"name":"origin","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"[Origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) corresponding to the newly created\ncontext for display purposes. The origin should be formatted like a URL,\nbut with only the scheme, host, and port (if necessary), like the value of\nthe [`url.origin`](url.html#urlorigin) property of a [`URL`](url.html#class-url) object. Most notably, this\nstring should omit the trailing slash, as that denotes a path.","default":"''","optional":true,"rest":false,"properties":[]},{"name":"codeGeneration","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"strings","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to false any calls to `eval` or function\nconstructors (`Function`, `GeneratorFunction`, etc) will throw an\n`EvalError`.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"wasm","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to false any attempt to compile a WebAssembly\nmodule will throw a `WebAssembly.CompileError`.","default":"true","optional":true,"rest":false,"properties":[]}]},{"name":"microtaskMode","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"If set to `afterEvaluate`, microtasks (tasks\nscheduled through `Promise`s and `async function`s) will be run immediately\nafter a script has run through [`script.runInContext()`](#scriptrunincontextcontextifiedobject-options).\nThey are included in the `timeout` and `breakOnSigint` scopes in that case.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"importModuleDynamically","type":{"text":"Function | vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","href":"vm.html#vmconstantsuse_main_context_default_loader","start":11,"end":55}]},"description":"Used to specify the how the modules should be loaded when `import()` is\ncalled in this context without a referrer script or module. This option is\npart of the experimental modules API. We do not recommend using it in a\nproduction environment. For detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"contextified object."}},"description":"If the given `contextObject` is an object, the `vm.createContext()` method will [prepare that\nobject](#what-does-it-mean-to-contextify-an-object) and return a reference to it so that it can be used in\ncalls to [`vm.runInContext()`](#vmrunincontextcode-contextifiedobject-options) or [`script.runInContext()`](#scriptrunincontextcontextifiedobject-options). Inside such\nscripts, the global object will be wrapped by the `contextObject`, retaining all of its\nexisting properties but also having the built-in objects and functions any\nstandard [global object](https://tc39.es/ecma262/#sec-global-object) has. Outside of scripts run by the vm module, global\nvariables will remain unchanged.\n\n```mjs\nimport { createContext, runInContext } from 'node:vm';\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\ncreateContext(context);\n\nrunInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n```\n\n```cjs\nconst { createContext, runInContext } = require('node:vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\ncreateContext(context);\n\nrunInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n```\n\nIf `contextObject` is omitted (or passed explicitly as `undefined`), a new,\nempty [contextified](#what-does-it-mean-to-contextify-an-object) object will be returned.\n\nWhen the global object in the newly created context is [contextified](#what-does-it-mean-to-contextify-an-object), it has some quirks\ncompared to ordinary global objects. For example, it cannot be frozen. To create a context\nwithout the contextifying quirks, pass [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify) as the `contextObject`\nargument. See the documentation of [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify) for details.\n\nThe `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.\n\nThe provided `name` and `origin` of the context are made visible through the\nInspector API.","summary":"If the given `contextObject` is an object, the `vm.createContext()` method will prepare that object and return a reference to it so that it can be used in calls to `vm.runInContext()` or `script.runInContext()`. Inside such scripts, the global object will be wrapped by the `contextObject`, retaining all of its existing properties but also having the built-in objects and functions any standard global object has. Outside of scripts run by the vm module, global variables will remain unchanged.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, runInContext } from 'node:vm';\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\ncreateContext(context);\n\nrunInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext } = require('node:vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\ncreateContext(context);\n\nrunInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3"}],"children":[]},{"kind":"method","id":"vmiscontextobject","name":"isContext","title":"`vm.isContext(object)`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.7"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"object","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"Returns `true` if the given `object` object has been [contextified](#what-does-it-mean-to-contextify-an-object) using\n[`vm.createContext()`](#vmcreatecontextcontextobject-options), or if it's the global object of a context created\nusing [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify).","summary":"Returns `true` if the given `object` object has been contextified using `vm.createContext()`, or if it's the global object of a context created using `vm.constants.DONT_CONTEXTIFY`.","examples":[],"children":[]},{"kind":"method","id":"vmmeasurememoryoptions","name":"measureMemory","title":"`vm.measureMemory([options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v13.10.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Optional.","default":null,"optional":true,"rest":false,"properties":[{"name":"mode","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"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.","default":"'summary'","optional":true,"rest":false,"properties":[]},{"name":"execution","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"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.","default":"'default'","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"If the memory is successfully measured, the promise will\nresolve with an object containing information about the memory usage.\nOtherwise it will be rejected with an `ERR_CONTEXT_NOT_INITIALIZED` error."}},"description":"Measure the memory known to V8 and used by all contexts known to the\ncurrent V8 isolate, or the main context.\n\nThe 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.\n\nThe returned result is different from the statistics returned by\n`v8.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.\n\n```mjs\nimport { createContext, measureMemory } from 'node:vm';\n// Measure the memory used by the main context.\nmeasureMemory({ mode: 'summary' })\n  // This is the same as vm.measureMemory()\n  .then((result) => {\n    // The current format is:\n    // {\n    //   total: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n    //   WebAssembly: { code: 0, metadata: 33962 },\n    // }\n    console.log(result);\n  });\n\nconst context = createContext({ a: 1 });\nmeasureMemory({ mode: 'detailed', execution: 'eager' }).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:', context.a);\n  // {\n  //   total: { jsMemoryEstimate: 1767100, jsMemoryRange: [1767100, 5440560] },\n  //   WebAssembly: { code: 0, metadata: 33962 },\n  //   current: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n  //   other: [{ jsMemoryEstimate: 165272, jsMemoryRange: [Array] }],\n  // }\n  console.log(result);\n});\n```\n\n```cjs\nconst { createContext, measureMemory } = require('node:vm');\n// Measure the memory used by the main context.\nmeasureMemory({ mode: 'summary' })\n  // This is the same as vm.measureMemory()\n  .then((result) => {\n    // The current format is:\n    // {\n    //   total: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n    //   WebAssembly: { code: 0, metadata: 33962 },\n    // }\n    console.log(result);\n  });\n\nconst context = createContext({ a: 1 });\nmeasureMemory({ mode: 'detailed', execution: 'eager' }).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:', context.a);\n  // {\n  //   total: { jsMemoryEstimate: 1767100, jsMemoryRange: [1767100, 5440560] },\n  //   WebAssembly: { code: 0, metadata: 33962 },\n  //   current: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n  //   other: [{ jsMemoryEstimate: 165272, jsMemoryRange: [Array] }],\n  // }\n  console.log(result);\n});\n```","summary":"Measure the memory known to V8 and used by all contexts known to the current V8 isolate, or the main context.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, measureMemory } from 'node:vm';\n// Measure the memory used by the main context.\nmeasureMemory({ mode: 'summary' })\n  // This is the same as vm.measureMemory()\n  .then((result) => {\n    // The current format is:\n    // {\n    //   total: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n    //   WebAssembly: { code: 0, metadata: 33962 },\n    // }\n    console.log(result);\n  });\n\nconst context = createContext({ a: 1 });\nmeasureMemory({ mode: 'detailed', execution: 'eager' }).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:', context.a);\n  // {\n  //   total: { jsMemoryEstimate: 1767100, jsMemoryRange: [1767100, 5440560] },\n  //   WebAssembly: { code: 0, metadata: 33962 },\n  //   current: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n  //   other: [{ jsMemoryEstimate: 165272, jsMemoryRange: [Array] }],\n  // }\n  console.log(result);\n});"},{"language":"cjs","displayName":null,"code":"const { createContext, measureMemory } = require('node:vm');\n// Measure the memory used by the main context.\nmeasureMemory({ mode: 'summary' })\n  // This is the same as vm.measureMemory()\n  .then((result) => {\n    // The current format is:\n    // {\n    //   total: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n    //   WebAssembly: { code: 0, metadata: 33962 },\n    // }\n    console.log(result);\n  });\n\nconst context = createContext({ a: 1 });\nmeasureMemory({ mode: 'detailed', execution: 'eager' }).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:', context.a);\n  // {\n  //   total: { jsMemoryEstimate: 1767100, jsMemoryRange: [1767100, 5440560] },\n  //   WebAssembly: { code: 0, metadata: 33962 },\n  //   current: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] },\n  //   other: [{ jsMemoryEstimate: 165272, jsMemoryRange: [Array] }],\n  // }\n  console.log(result);\n});"}],"children":[]},{"kind":"method","id":"vmrunincontextcode-contextifiedobject-options","name":"runInContext","title":"`vm.runInContext(code, contextifiedObject[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.7.0","v20.12.0"],"prUrl":"https://github.com/nodejs/node/pull/51244","commit":null,"description":"Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."},{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/40249","commit":null,"description":"Added support for import attributes to the `importModuleDynamically` parameter."},{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakOnSigint` option is supported now."}],"signature":{"parameters":[{"name":"code","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The JavaScript code to compile and run.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"contextifiedObject","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The [contextified](#what-does-it-mean-to-contextify-an-object) object that will be used\nas the `global` when the `code` is compiled and run.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object | string","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"filename","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the filename used in stack traces produced\nby this script.","default":"'evalmachine.<anonymous>'","optional":true,"rest":false,"properties":[]},{"name":"lineOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the line number offset that is displayed\nin stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"columnOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the first-line column number offset that\nis displayed in stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"displayErrors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true`, if an [`Error`](errors.html#class-error) occurs\nwhile compiling the `code`, the line of code causing the error is attached\nto the stack trace.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to execute `code`\nbefore terminating execution. If execution is terminated, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"cachedData","type":{"text":"Buffer | TypedArray | DataView","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30}]},"description":"Provides an optional `Buffer` or\n`TypedArray`, or `DataView` with V8's code cache data for the supplied\nsource.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"importModuleDynamically","type":{"text":"Function | vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","href":"vm.html#vmconstantsuse_main_context_default_loader","start":11,"end":55}]},"description":"Used to specify the how the modules should be loaded during the evaluation\nof this script when `import()` is called. This option is part of the\nexperimental modules API. We do not recommend using it in a production\nenvironment. For detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"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](#what-does-it-mean-to-contextify-an-object) using the [`vm.createContext()`](#vmcreatecontextcontextobject-options) method.\n\nIf `options` is a string, then it specifies the filename.\n\nThe following example compiles and executes different scripts using a single\n[contextified](#what-does-it-mean-to-contextify-an-object) object:\n\n```mjs\nimport { createContext, runInContext } from 'node:vm';\n\nconst contextObject = { globalVar: 1 };\ncreateContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n```\n\n```cjs\nconst { createContext, runInContext } = require('node:vm');\n\nconst contextObject = { globalVar: 1 };\ncreateContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n```","summary":"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 `vm.createContext()` method.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, runInContext } from 'node:vm';\n\nconst contextObject = { globalVar: 1 };\ncreateContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext } = require('node:vm');\n\nconst contextObject = { globalVar: 1 };\ncreateContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }"}],"children":[]},{"kind":"method","id":"vmruninnewcontextcode-contextobject-options","name":"runInNewContext","title":"`vm.runInNewContext(code[, contextObject[, options]])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.8.0","v20.18.0"],"prUrl":"https://github.com/nodejs/node/pull/54394","commit":null,"description":"The `contextObject` argument now accepts `vm.constants.DONT_CONTEXTIFY`."},{"versions":["v21.7.0","v20.12.0"],"prUrl":"https://github.com/nodejs/node/pull/51244","commit":null,"description":"Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."},{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/40249","commit":null,"description":"Added support for import attributes to the `importModuleDynamically` parameter."},{"versions":["v14.6.0"],"prUrl":"https://github.com/nodejs/node/pull/34023","commit":null,"description":"The `microtaskMode` option is supported now."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/19016","commit":null,"description":"The `contextCodeGeneration` option is supported now."},{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakOnSigint` option is supported now."}],"signature":{"parameters":[{"name":"code","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The JavaScript code to compile and run.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"contextObject","type":{"text":"Object | vm.constants.DONT_CONTEXTIFY | undefined","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"vm.constants.DONT_CONTEXTIFY","href":"vm.html#vmconstantsdont_contextify","start":9,"end":37},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":40,"end":49}]},"description":"Either [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify) or an object that will be [contextified](#what-does-it-mean-to-contextify-an-object).\nIf `undefined`, an empty contextified object will be created for backwards compatibility.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object | string","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"filename","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the filename used in stack traces produced\nby this script.","default":"'evalmachine.<anonymous>'","optional":true,"rest":false,"properties":[]},{"name":"lineOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the line number offset that is displayed\nin stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"columnOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the first-line column number offset that\nis displayed in stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"displayErrors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true`, if an [`Error`](errors.html#class-error) occurs\nwhile compiling the `code`, the line of code causing the error is attached\nto the stack trace.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to execute `code`\nbefore terminating execution. If execution is terminated, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"contextName","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Human-readable name of the newly created context.","default":"`'VM Context i'`, where `i` is an ascending numerical index of the created context","optional":true,"rest":false,"properties":[]},{"name":"contextOrigin","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"[Origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) corresponding to the newly\ncreated context for display purposes. The origin should be formatted like a\nURL, but with only the scheme, host, and port (if necessary), like the\nvalue of the [`url.origin`](url.html#urlorigin) property of a [`URL`](url.html#class-url) object. Most notably,\nthis string should omit the trailing slash, as that denotes a path.","default":"''","optional":true,"rest":false,"properties":[]},{"name":"contextCodeGeneration","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"strings","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to false any calls to `eval` or function\nconstructors (`Function`, `GeneratorFunction`, etc) will throw an\n`EvalError`.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"wasm","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to false any attempt to compile a WebAssembly\nmodule will throw a `WebAssembly.CompileError`.","default":"true","optional":true,"rest":false,"properties":[]}]},{"name":"cachedData","type":{"text":"Buffer | TypedArray | DataView","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30}]},"description":"Provides an optional `Buffer` or\n`TypedArray`, or `DataView` with V8's code cache data for the supplied\nsource.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"importModuleDynamically","type":{"text":"Function | vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","href":"vm.html#vmconstantsuse_main_context_default_loader","start":11,"end":55}]},"description":"Used to specify the how the modules should be loaded during the evaluation\nof this script when `import()` is called. This option is part of the\nexperimental modules API. We do not recommend using it in a production\nenvironment. For detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"microtaskMode","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"If set to `afterEvaluate`, microtasks (tasks\nscheduled through `Promise`s and `async function`s) will be run immediately\nafter the script has run. They are included in the `timeout` and\n`breakOnSigint` scopes in that case.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the result of the very last statement executed in the script."}},"description":"This method is a shortcut to\n`(new vm.Script(code, options)).runInContext(vm.createContext(options), options)`.\nIf `options` is a string, then it specifies the filename.\n\nIt does several things at once:\n\n1. Creates a new context.\n2. If `contextObject` is an object, [contextifies](#what-does-it-mean-to-contextify-an-object) it with the new context.\n   If `contextObject` is undefined, creates a new object and [contextifies](#what-does-it-mean-to-contextify-an-object) it.\n   If `contextObject` is [`vm.constants.DONT_CONTEXTIFY`](#vmconstantsdont_contextify), don't [contextify](#what-does-it-mean-to-contextify-an-object) anything.\n3. Compiles the code as a `vm.Script`\n4. Runs the compiled code within the created context. The code does not have access to the scope in\n   which this method is called.\n5. Returns the result.\n\nThe following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the `contextObject`.\n\n```mjs\nimport { runInNewContext, constants } from 'node:vm';\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2,\n};\n\nrunInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n\n// This would throw if the context is created from a contextified object.\n// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that\n// can be frozen.\nconst frozenContext = runInNewContext(\n  'Object.freeze(globalThis); globalThis;',\n  constants.DONT_CONTEXTIFY,\n);\n```\n\n```cjs\nconst { runInNewContext, constants } = require('node:vm');\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2,\n};\n\nrunInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n\n// This would throw if the context is created from a contextified object.\n// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that\n// can be frozen.\nconst frozenContext = runInNewContext(\n  'Object.freeze(globalThis); globalThis;',\n  constants.DONT_CONTEXTIFY,\n);\n```","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import { runInNewContext, constants } from 'node:vm';\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2,\n};\n\nrunInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n\n// This would throw if the context is created from a contextified object.\n// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that\n// can be frozen.\nconst frozenContext = runInNewContext(\n  'Object.freeze(globalThis); globalThis;',\n  constants.DONT_CONTEXTIFY,\n);"},{"language":"cjs","displayName":null,"code":"const { runInNewContext, constants } = require('node:vm');\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2,\n};\n\nrunInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n\n// This would throw if the context is created from a contextified object.\n// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that\n// can be frozen.\nconst frozenContext = runInNewContext(\n  'Object.freeze(globalThis); globalThis;',\n  constants.DONT_CONTEXTIFY,\n);"}],"children":[]},{"kind":"method","id":"vmruninthiscontextcode-options","name":"runInThisContext","title":"`vm.runInThisContext(code[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.3.1"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.7.0","v20.12.0"],"prUrl":"https://github.com/nodejs/node/pull/51244","commit":null,"description":"Added support for `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`."},{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/40249","commit":null,"description":"Added support for import attributes to the `importModuleDynamically` parameter."},{"versions":["v6.3.0"],"prUrl":"https://github.com/nodejs/node/pull/6635","commit":null,"description":"The `breakOnSigint` option is supported now."}],"signature":{"parameters":[{"name":"code","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The JavaScript code to compile and run.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object | string","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"filename","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the filename used in stack traces produced\nby this script.","default":"'evalmachine.<anonymous>'","optional":true,"rest":false,"properties":[]},{"name":"lineOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the line number offset that is displayed\nin stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"columnOffset","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Specifies the first-line column number offset that\nis displayed in stack traces produced by this script.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"displayErrors","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When `true`, if an [`Error`](errors.html#class-error) occurs\nwhile compiling the `code`, the line of code causing the error is attached\nto the stack trace.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Specifies the number of milliseconds to execute `code`\nbefore terminating execution. If execution is terminated, an [`Error`](errors.html#class-error)\nwill be thrown. This value must be a strictly positive integer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"breakOnSigint","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, receiving `SIGINT`\n(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an\n[`Error`](errors.html#class-error). Existing handlers for the event that have been attached via\n`process.on('SIGINT')` are disabled during script execution, but continue to\nwork after that.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"cachedData","type":{"text":"Buffer | TypedArray | DataView","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30}]},"description":"Provides an optional `Buffer` or\n`TypedArray`, or `DataView` with V8's code cache data for the supplied\nsource.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"importModuleDynamically","type":{"text":"Function | vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","href":"vm.html#vmconstantsuse_main_context_default_loader","start":11,"end":55}]},"description":"Used to specify the how the modules should be loaded during the evaluation\nof this script when `import()` is called. This option is part of the\nexperimental modules API. We do not recommend using it in a production\nenvironment. For detailed information, see\n[Support of dynamic `import()` in compilation APIs](#support-of-dynamic-import-in-compilation-apis).","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the result of the very last statement executed in the script."}},"description":"`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.\n\nIf `options` is a string, then it specifies the filename.\n\nThe following example illustrates using both `vm.runInThisContext()` and\nthe JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code:\n\n```mjs\nimport { runInThisContext } from 'node:vm';\nlet localVar = 'initial value';\n\nconst vmResult = 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```\n\n```cjs\nconst { runInThisContext } = require('node:vm');\nlet localVar = 'initial value';\n\nconst vmResult = 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```\n\nBecause `vm.runInThisContext()` does not have access to the local scope,\n`localVar` is unchanged. In contrast, a direct `eval()` call *does* have access\nto the local scope, so the value `localVar` is changed. In this way\n`vm.runInThisContext()` is much like an [indirect `eval()` call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_indirect_eval), e.g.\n`(0,eval)('code')`.","summary":"`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.","examples":[{"language":"mjs","displayName":null,"code":"import { runInThisContext } from 'node:vm';\nlet localVar = 'initial value';\n\nconst vmResult = 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'"},{"language":"cjs","displayName":null,"code":"const { runInThisContext } = require('node:vm');\nlet localVar = 'initial value';\n\nconst vmResult = 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'"}],"children":[]},{"kind":"section","id":"example-running-an-http-server-within-a-vm","name":"Example: Running an HTTP server within a VM","title":"Example: Running an HTTP server within a VM","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"When using either [`script.runInThisContext()`](#scriptruninthiscontextoptions) or\n[`vm.runInThisContext()`](#vmruninthiscontextcode-options), the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.\n\nIn 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:\n\n```mjs\nimport { runInThisContext } from 'node:vm';\nimport { createRequire } from 'node:module';\n\nconst require = createRequire(import.meta.url);\n\nconst code = `\n((require) => {\n  const { createServer } = require('node:http');\n\n  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\nrunInThisContext(code)(require);\n```\n\n```cjs\nconst { runInThisContext } = require('node:vm');\n\nconst code = `\n((require) => {\n  const { createServer } = require('node:http');\n\n  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\nrunInThisContext(code)(require);\n```\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.","summary":"When using either `script.runInThisContext()` or `vm.runInThisContext()`, the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.","examples":[{"language":"mjs","displayName":null,"code":"import { runInThisContext } from 'node:vm';\nimport { createRequire } from 'node:module';\n\nconst require = createRequire(import.meta.url);\n\nconst code = `\n((require) => {\n  const { createServer } = require('node:http');\n\n  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\nrunInThisContext(code)(require);"},{"language":"cjs","displayName":null,"code":"const { runInThisContext } = require('node:vm');\n\nconst code = `\n((require) => {\n  const { createServer } = require('node:http');\n\n  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\nrunInThisContext(code)(require);"}],"children":[]},{"kind":"section","id":"what-does-it-mean-to-contextify-an-object","name":"What does it mean to \"contextify\" an object?","title":"What does it mean to \"contextify\" an object?","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the [V8 Embedder's Guide](https://v8.dev/docs/embed#contexts):\n\n> In V8, a context is an execution environment that allows separate, unrelated,\n> JavaScript applications to run in a single instance of V8. You must explicitly\n> specify the context in which you want any JavaScript code to be run.\n\nWhen the method `vm.createContext()` is called with an object, the `contextObject` argument\nwill be used to wrap the global object of a new instance of a V8 Context\n(if `contextObject` is `undefined`, a new object will be created from the current context\nbefore its contextified). This V8 Context provides the `code` run using the `node:vm`\nmodule's methods with an isolated global environment within which it can operate.\nThe process of creating the V8 Context and associating it with the `contextObject`\nin the outer context is what this document refers to as \"contextifying\" the object.\n\nThe contextifying would introduce some quirks to the `globalThis` value in the context.\nFor example, it cannot be frozen, and it is not reference equal to the `contextObject`\nin the outer context.\n\n```mjs\nimport { createContext, runInContext } from 'node:vm';\n\n// An undefined `contextObject` option makes the global object contextified.\nconst context = createContext();\nconsole.log(runInContext('globalThis', context) === context);  // false\n// A contextified global object cannot be frozen.\ntry {\n  runInContext('Object.freeze(globalThis);', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // TypeError: Cannot freeze\n}\nconsole.log(runInContext('globalThis.foo = 1; foo;', context));  // 1\n```\n\n```cjs\nconst { createContext, runInContext } = require('node:vm');\n\n// An undefined `contextObject` option makes the global object contextified.\nconst context = createContext();\nconsole.log(runInContext('globalThis', context) === context);  // false\n// A contextified global object cannot be frozen.\ntry {\n  runInContext('Object.freeze(globalThis);', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // TypeError: Cannot freeze\n}\nconsole.log(runInContext('globalThis.foo = 1; foo;', context));  // 1\n```\n\nTo create a context with an ordinary global object and get access to a global proxy in\nthe outer context with fewer quirks, specify `vm.constants.DONT_CONTEXTIFY` as the\n`contextObject` argument.","summary":"All JavaScript executed within Node.js runs within the scope of a \"context\". According to the V8 Embedder's Guide:","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, runInContext } from 'node:vm';\n\n// An undefined `contextObject` option makes the global object contextified.\nconst context = createContext();\nconsole.log(runInContext('globalThis', context) === context);  // false\n// A contextified global object cannot be frozen.\ntry {\n  runInContext('Object.freeze(globalThis);', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // TypeError: Cannot freeze\n}\nconsole.log(runInContext('globalThis.foo = 1; foo;', context));  // 1"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext } = require('node:vm');\n\n// An undefined `contextObject` option makes the global object contextified.\nconst context = createContext();\nconsole.log(runInContext('globalThis', context) === context);  // false\n// A contextified global object cannot be frozen.\ntry {\n  runInContext('Object.freeze(globalThis);', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // TypeError: Cannot freeze\n}\nconsole.log(runInContext('globalThis.foo = 1; foo;', context));  // 1"}],"children":[{"kind":"property","id":"vmconstantsdont_contextify","name":"DONT_CONTEXTIFY","title":"`vm.constants.DONT_CONTEXTIFY`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"This constant, when used as the `contextObject` argument in vm APIs, instructs Node.js to create\na context without wrapping its global object with another object in a Node.js-specific manner.\nAs a result, the `globalThis` value inside the new context would behave more closely to an ordinary\none.\n\n```mjs\nimport { createContext, runInContext, constants } from 'node:vm';\n\n// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.\nconst context = createContext(constants.DONT_CONTEXTIFY);\nrunInContext('Object.freeze(globalThis);', context);\ntry {\n  runInContext('bar = 1; bar;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: bar is not defined\n}\n```\n\n```cjs\nconst { createContext, runInContext, constants } = require('node:vm');\n\n// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.\nconst context = createContext(constants.DONT_CONTEXTIFY);\nrunInContext('Object.freeze(globalThis);', context);\ntry {\n  runInContext('bar = 1; bar;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: bar is not defined\n}\n```\n\nWhen `vm.constants.DONT_CONTEXTIFY` is used as the `contextObject` argument to [`vm.createContext()`](#vmcreatecontextcontextobject-options),\nthe returned object is a proxy-like object to the global object in the newly created context with\nfewer Node.js-specific quirks. It is reference equal to the `globalThis` value in the new context,\ncan be modified from outside the context, and can be used to access built-ins in the new context directly.\n\n```mjs\nimport { createContext, runInContext, constants } from 'node:vm';\n\nconst context = createContext(constants.DONT_CONTEXTIFY);\n\n// Returned object is reference equal to globalThis in the new context.\nconsole.log(runInContext('globalThis', context) === context);  // true\n\n// Can be used to access globals in the new context directly.\nconsole.log(context.Array);  // [Function: Array]\nrunInContext('foo = 1;', context);\nconsole.log(context.foo);  // 1\ncontext.bar = 1;\nconsole.log(runInContext('bar;', context));  // 1\n\n// Can be frozen and it affects the inner context.\nObject.freeze(context);\ntry {\n  runInContext('baz = 1; baz;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: baz is not defined\n}\n```\n\n```cjs\nconst { createContext, runInContext, constants } = require('node:vm');\n\nconst context = createContext(constants.DONT_CONTEXTIFY);\n\n// Returned object is reference equal to globalThis in the new context.\nconsole.log(runInContext('globalThis', context) === context);  // true\n\n// Can be used to access globals in the new context directly.\nconsole.log(context.Array);  // [Function: Array]\nrunInContext('foo = 1;', context);\nconsole.log(context.foo);  // 1\ncontext.bar = 1;\nconsole.log(runInContext('bar;', context));  // 1\n\n// Can be frozen and it affects the inner context.\nObject.freeze(context);\ntry {\n  runInContext('baz = 1; baz;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: baz is not defined\n}\n```","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, runInContext, constants } from 'node:vm';\n\n// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.\nconst context = createContext(constants.DONT_CONTEXTIFY);\nrunInContext('Object.freeze(globalThis);', context);\ntry {\n  runInContext('bar = 1; bar;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: bar is not defined\n}"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext, constants } = require('node:vm');\n\n// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.\nconst context = createContext(constants.DONT_CONTEXTIFY);\nrunInContext('Object.freeze(globalThis);', context);\ntry {\n  runInContext('bar = 1; bar;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: bar is not defined\n}"},{"language":"mjs","displayName":null,"code":"import { createContext, runInContext, constants } from 'node:vm';\n\nconst context = createContext(constants.DONT_CONTEXTIFY);\n\n// Returned object is reference equal to globalThis in the new context.\nconsole.log(runInContext('globalThis', context) === context);  // true\n\n// Can be used to access globals in the new context directly.\nconsole.log(context.Array);  // [Function: Array]\nrunInContext('foo = 1;', context);\nconsole.log(context.foo);  // 1\ncontext.bar = 1;\nconsole.log(runInContext('bar;', context));  // 1\n\n// Can be frozen and it affects the inner context.\nObject.freeze(context);\ntry {\n  runInContext('baz = 1; baz;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: baz is not defined\n}"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext, constants } = require('node:vm');\n\nconst context = createContext(constants.DONT_CONTEXTIFY);\n\n// Returned object is reference equal to globalThis in the new context.\nconsole.log(runInContext('globalThis', context) === context);  // true\n\n// Can be used to access globals in the new context directly.\nconsole.log(context.Array);  // [Function: Array]\nrunInContext('foo = 1;', context);\nconsole.log(context.foo);  // 1\ncontext.bar = 1;\nconsole.log(runInContext('bar;', context));  // 1\n\n// Can be frozen and it affects the inner context.\nObject.freeze(context);\ntry {\n  runInContext('baz = 1; baz;', context);\n} catch (e) {\n  console.log(`${e.constructor.name}: ${e.message}`); // ReferenceError: baz is not defined\n}"}],"children":[]}]},{"kind":"section","id":"timeout-interactions-with-asynchronous-tasks-and-promises","name":"Timeout interactions with asynchronous tasks and Promises","title":"Timeout interactions with asynchronous tasks and Promises","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`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\n`breakOnSigint` options.\n\nFor 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:\n\n```mjs\nimport { runInNewContext } from 'node:vm';\n\nfunction loop() {\n  console.log('entering loop');\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5 },\n);\n// This is printed *before* 'entering infinite loop' (!)\nconsole.log('done executing');\n```\n\n```cjs\nconst { runInNewContext } = require('node:vm');\n\nfunction loop() {\n  console.log('entering loop');\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5 },\n);\n// This is printed *before* 'entering infinite loop' (!)\nconsole.log('done executing');\n```\n\nThis can be addressed by passing `microtaskMode: 'afterEvaluate'` to the code\nthat creates the `Context`:\n\n```mjs\nimport { runInNewContext } from 'node:vm';\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5, microtaskMode: 'afterEvaluate' },\n);\n```\n\n```cjs\nconst { runInNewContext } = require('node:vm');\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5, microtaskMode: 'afterEvaluate' },\n);\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\n`vm.Context`, so e.g. [`vm.runInThisContext()`](#vmruninthiscontextcode-options) does not take this option.\n\nPromise 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.\n\nIf asynchronous scheduling functions such as `process.nextTick()`,\n`queueMicrotask()`, `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.","summary":"`Promise`s and `async function`s can schedule tasks run by the JavaScript engine asynchronously. By default, these tasks are run after all JavaScript functions on the current stack are done executing. This allows escaping the functionality of the `timeout` and `breakOnSigint` options.","examples":[{"language":"mjs","displayName":null,"code":"import { runInNewContext } from 'node:vm';\n\nfunction loop() {\n  console.log('entering loop');\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5 },\n);\n// This is printed *before* 'entering infinite loop' (!)\nconsole.log('done executing');"},{"language":"cjs","displayName":null,"code":"const { runInNewContext } = require('node:vm');\n\nfunction loop() {\n  console.log('entering loop');\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5 },\n);\n// This is printed *before* 'entering infinite loop' (!)\nconsole.log('done executing');"},{"language":"mjs","displayName":null,"code":"import { runInNewContext } from 'node:vm';\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5, microtaskMode: 'afterEvaluate' },\n);"},{"language":"cjs","displayName":null,"code":"const { runInNewContext } = require('node:vm');\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nrunInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5, microtaskMode: 'afterEvaluate' },\n);"}],"children":[{"kind":"section","id":"when-microtaskmode-is-afterevaluate-beware-sharing-promises-between-contexts","name":"When microtaskMode is 'afterEvaluate', beware sharing Promises between Contexts","title":"When `microtaskMode` is `'afterEvaluate'`, beware sharing Promises between Contexts","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"In `'afterEvaluate'` mode, the `Context` has its own microtask queue, separate\nfrom the global microtask queue used by the outer (main) context. While this\nmode is necessary to enforce `timeout` and enable `breakOnSigint` with\nasynchronous tasks, it also makes sharing promises between contexts challenging.\n\nIn the example below, a promise is created in the inner context and shared with\nthe outer context. When the outer context `await` on the promise, the execution\nflow of the outer context is disrupted in a surprising way: the log statement\nis never executed.\n\n```mjs\nimport { createContext, runInContext } from 'node:vm';\n\nconst inner_context = createContext({}, { microtaskMode: 'afterEvaluate' });\n\n// runInContext() returns a Promise created in the inner context.\nconst inner_promise = runInContext('Promise.resolve()', inner_context);\n\n// As part of performing `await`, the JavaScript runtime must enqueue a task\n// on the microtask queue of the context where `inner_promise` was created.\n// A task is added on the inner microtask queue, but **it will not be run\n// automatically**: this task will remain pending indefinitely.\n//\n// Since the outer microtask queue is empty, execution in the outer module\n// falls through, and the log statement below is never executed.\nawait inner_promise;\n\nconsole.log('this will NOT be printed');\n```\n\n```cjs\nconst { createContext, runInContext } = require('node:vm');\n\n// runInContext() returns a Promise created in the inner context.\nconst inner_context = createContext({}, { microtaskMode: 'afterEvaluate' });\n\n(async () => {\n  const inner_promise = runInContext('Promise.resolve()', inner_context);\n\n  // As part of performing `await`, the JavaScript runtime must enqueue a task\n  // on the microtask queue of the context where `inner_promise` was created.\n  // A task is added on the inner microtask queue, but **it will not be run\n  // automatically**: this task will remain pending indefinitely.\n  //\n  // Since the outer microtask queue is empty, execution in the outer module\n  // falls through, and the log statement below is never executed.\n  await inner_promise;\n\n  console.log('this will NOT be printed');\n})();\n```\n\nTo successfully share promises between contexts with different microtask queues,\nit is necessary to ensure that tasks on the inner microtask queue will be run\n**whenever** the outer context enqueues a task on the inner microtask queue.\n\nThe tasks on the microtask queue of a given context are run whenever\n`runInContext()` or `SourceTextModule.evaluate()` are invoked on a script or\nmodule using this context. In our example, the normal execution flow can be\nrestored by scheduling a second call to `runInContext()` *before* `await\ninner_promise`.\n\n```mjs\n// Schedule `runInContext()` to manually drain the inner context microtask\n// queue; it will run after the `await` statement below.\nsetImmediate(() => {\n  vm.runInContext('', context);\n});\n\nawait inner_promise;\n\nconsole.log('OK');\n```\n\n**Note:** Strictly speaking, in this mode, `node:vm` departs from the letter of\nthe ECMAScript specification for [enqueuing jobs](https://tc39.es/ecma262/#sec-hostenqueuepromisejob), by allowing asynchronous\ntasks from different contexts to run in a different order than they were\nenqueued.","summary":"In `'afterEvaluate'` mode, the `Context` has its own microtask queue, separate from the global microtask queue used by the outer (main) context. While this mode is necessary to enforce `timeout` and enable `breakOnSigint` with asynchronous tasks, it also makes sharing promises between contexts challenging.","examples":[{"language":"mjs","displayName":null,"code":"import { createContext, runInContext } from 'node:vm';\n\nconst inner_context = createContext({}, { microtaskMode: 'afterEvaluate' });\n\n// runInContext() returns a Promise created in the inner context.\nconst inner_promise = runInContext('Promise.resolve()', inner_context);\n\n// As part of performing `await`, the JavaScript runtime must enqueue a task\n// on the microtask queue of the context where `inner_promise` was created.\n// A task is added on the inner microtask queue, but **it will not be run\n// automatically**: this task will remain pending indefinitely.\n//\n// Since the outer microtask queue is empty, execution in the outer module\n// falls through, and the log statement below is never executed.\nawait inner_promise;\n\nconsole.log('this will NOT be printed');"},{"language":"cjs","displayName":null,"code":"const { createContext, runInContext } = require('node:vm');\n\n// runInContext() returns a Promise created in the inner context.\nconst inner_context = createContext({}, { microtaskMode: 'afterEvaluate' });\n\n(async () => {\n  const inner_promise = runInContext('Promise.resolve()', inner_context);\n\n  // As part of performing `await`, the JavaScript runtime must enqueue a task\n  // on the microtask queue of the context where `inner_promise` was created.\n  // A task is added on the inner microtask queue, but **it will not be run\n  // automatically**: this task will remain pending indefinitely.\n  //\n  // Since the outer microtask queue is empty, execution in the outer module\n  // falls through, and the log statement below is never executed.\n  await inner_promise;\n\n  console.log('this will NOT be printed');\n})();"},{"language":"mjs","displayName":null,"code":"// Schedule `runInContext()` to manually drain the inner context microtask\n// queue; it will run after the `await` statement below.\nsetImmediate(() => {\n  vm.runInContext('', context);\n});\n\nawait inner_promise;\n\nconsole.log('OK');"}],"children":[]}]},{"kind":"section","id":"support-of-dynamic-import-in-compilation-apis","name":"Support of dynamic import() in compilation APIs","title":"Support of dynamic `import()` in compilation APIs","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The following APIs support an `importModuleDynamically` option to enable dynamic\n`import()` in code compiled by the vm module.\n\n* `new vm.Script`\n* `vm.compileFunction()`\n* `new vm.SourceTextModule`\n* `vm.runInThisContext()`\n* `vm.runInContext()`\n* `vm.runInNewContext()`\n* `vm.createContext()`\n\nThis option is still part of the experimental modules API. We do not recommend\nusing it in a production environment.","summary":"The following APIs support an `importModuleDynamically` option to enable dynamic `import()` in code compiled by the vm module.","examples":[],"children":[{"kind":"section","id":"when-the-importmoduledynamically-option-is-not-specified-or-undefined","name":"When the importModuleDynamically option is not specified or undefined","title":"When the `importModuleDynamically` option is not specified or undefined","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"If this option is not specified, or if it's `undefined`, code containing\n`import()` 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\n[`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`](errors.html#err_vm_dynamic_import_callback_missing).","summary":"If this option is not specified, or if it's `undefined`, code containing `import()` can still be compiled by the vm APIs, but when the compiled code is executed and it actually calls `import()`, the result will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`.","examples":[],"children":[]},{"kind":"section","id":"when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader","name":"When importModuleDynamically is vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER","title":"When `importModuleDynamically` is `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"This option is currently not supported for `vm.SourceTextModule`.\n\nWith 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.\n\nThis 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.\n\n```cjs\nconst { 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```\n\n```mjs\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```\n\nThis option also allows the script or function to load user modules:\n\n```mjs\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```\n\n```cjs\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```\n\nThere are a few caveats with loading user modules using the default loader\nfrom the main context:\n\n1. The module being resolved would be relative to the `filename` option passed\n   to `vm.Script` or `vm.compileFunction()`. The resolution can work with a\n   `filename` that's either an absolute path or a URL string.  If `filename` is\n   a string that's neither an absolute path or a URL, or if it's undefined,\n   the resolution will be relative to the current working directory\n   of the process. In the case of `vm.createContext()`, the resolution is always\n   relative to the current working directory since this option is only used when\n   there isn't a referrer script or module.\n2. For any given `filename` that resolves to a specific path, once the process\n   manages to load a particular module from that path, the result may be cached,\n   and subsequent load of the same module from the same path would return the\n   same thing. If the `filename` is a URL string, the cache would not be hit\n   if it has different search parameters. For `filename`s that are not URL\n   strings, there is currently no way to bypass the caching behavior.","summary":"This option is currently not supported for `vm.SourceTextModule`.","examples":[{"language":"cjs","displayName":null,"code":"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);"},{"language":"mjs","displayName":null,"code":"import { 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);"},{"language":"mjs","displayName":null,"code":"import { 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);"},{"language":"cjs","displayName":null,"code":"const { 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);"}],"children":[]},{"kind":"section","id":"when-importmoduledynamically-is-a-function","name":"When importModuleDynamically is a function","title":"When `importModuleDynamically` is a function","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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\n[`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`](errors.html#err_vm_dynamic_import_callback_missing_flag).\n\nThe callback `importModuleDynamically(specifier, referrer, importAttributes)`\nhas the following signature:\n\n* `specifier` {string} specifier passed to `import()`\n* `referrer` {vm.Script | Function | vm.SourceTextModule | Object}\n  The referrer is the compiled `vm.Script` for `new vm.Script`,\n  `vm.runInThisContext`, `vm.runInContext` and `vm.runInNewContext`. It's the\n  compiled `Function` for `vm.compileFunction`, the compiled\n  `vm.SourceTextModule` for `new vm.SourceTextModule`, and the context `Object`\n  for `vm.createContext()`.\n* `importAttributes` {Object} The `\"with\"` value passed to the\n  [`optionsExpression`](https://tc39.es/proposal-import-attributes/#sec-evaluate-import-call) optional parameter, or an empty object if no value was\n  provided.\n* `phase` {string} The phase of the dynamic import (`\"source\"` or `\"evaluation\"`).\n* Returns: {Module Namespace Object | vm.Module} Returning a `vm.Module` is\n  recommended in order to take advantage of error tracking, and to avoid issues\n  with namespaces that contain `then` function exports.\n\n```mjs\n// 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\n```cjs\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```","summary":"When `importModuleDynamically` is a function, it will be invoked when `import()` is called in the compiled code for users to customize how the requested module should be compiled and evaluated. Currently, the Node.js instance must be launched with the `--experimental-vm-modules` flag for this option to work. If the flag isn't set, this callback will be ignored. If the code evaluated actually calls to `import()`, the result will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`.","examples":[{"language":"mjs","displayName":null,"code":"// 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' } }"},{"language":"cjs","displayName":null,"code":"// 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})();"}],"children":[]}]}]}