1{ 2 "type": "module", 3 "source": "doc/api/vm.md", 4 "modules": [ 5 { 6 "textRaw": "VM (executing JavaScript)", 7 "name": "vm", 8 "introduced_in": "v0.10.0", 9 "stability": 2, 10 "stabilityText": "Stable", 11 "desc": "<p><strong>Source Code:</strong> <a href=\"https://github.com/nodejs/node/blob/v18.20.1/lib/vm.js\">lib/vm.js</a></p>\n<p>The <code>node:vm</code> module enables compiling and running code within V8 Virtual\nMachine contexts.</p>\n<p><strong class=\"critical\">The <code>node:vm</code> module is not a security\nmechanism. Do not use it to run untrusted code.</strong></p>\n<p>JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.</p>\n<p>A 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.</p>\n<p>One can provide the context by <a href=\"#what-does-it-mean-to-contextify-an-object\"><em>contextifying</em></a> 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.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\nvm.createContext(context); // Contextify the object.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the context.\n// Initially, x has the value 2 because that is the value of context.x.\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n</code></pre>", 12 "classes": [ 13 { 14 "textRaw": "Class: `vm.Script`", 15 "type": "class", 16 "name": "vm.Script", 17 "meta": { 18 "added": [ 19 "v0.3.1" 20 ], 21 "changes": [] 22 }, 23 "desc": "<p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be\nexecuted in specific contexts.</p>", 24 "properties": [ 25 { 26 "textRaw": "`cachedDataRejected` {boolean|undefined}", 27 "type": "boolean|undefined", 28 "name": "cachedDataRejected", 29 "meta": { 30 "added": [ 31 "v5.7.0" 32 ], 33 "changes": [] 34 }, 35 "desc": "<p>When <code>cachedData</code> is supplied to create the <code>vm.Script</code>, this value will be set\nto either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.\nOtherwise the value is <code>undefined</code>.</p>" 36 }, 37 { 38 "textRaw": "`sourceMapURL` {string|undefined}", 39 "type": "string|undefined", 40 "name": "sourceMapURL", 41 "meta": { 42 "added": [ 43 "v18.13.0" 44 ], 45 "changes": [] 46 }, 47 "desc": "<p>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.</p>\n<pre><code class=\"language-mjs\">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\n</code></pre>\n<pre><code class=\"language-cjs\">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\n</code></pre>" 48 } 49 ], 50 "methods": [ 51 { 52 "textRaw": "`script.createCachedData()`", 53 "type": "method", 54 "name": "createCachedData", 55 "meta": { 56 "added": [ 57 "v10.6.0" 58 ], 59 "changes": [] 60 }, 61 "signatures": [ 62 { 63 "return": { 64 "textRaw": "Returns: {Buffer}", 65 "name": "return", 66 "type": "Buffer" 67 }, 68 "params": [] 69 } 70 ], 71 "desc": "<p>Creates a code cache that can be used with the <code>Script</code> constructor's\n<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called at any\ntime and any number of times.</p>\n<p>The code cache of the <code>Script</code> 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 <code>Script</code> instances multiple times.</p>\n<p>Functions in the <code>Script</code> source can be marked as lazily compiled and they are\nnot compiled at construction of the <code>Script</code>. 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 <code>Script</code> that it can use to speed up\nfuture compilations.</p>\n<pre><code class=\"language-js\">const script = new vm.Script(`\nfunction add(a, b) {\n return a + b;\n}\n\nconst x = add(1, 2);\n`);\n\nconst cacheWithoutAdd = script.createCachedData();\n// In `cacheWithoutAdd` the function `add()` is marked for full compilation\n// upon invocation.\n\nscript.runInThisContext();\n\nconst cacheWithAdd = script.createCachedData();\n// `cacheWithAdd` contains fully compiled function `add()`.\n</code></pre>" 72 }, 73 { 74 "textRaw": "`script.runInContext(contextifiedObject[, options])`", 75 "type": "method", 76 "name": "runInContext", 77 "meta": { 78 "added": [ 79 "v0.3.1" 80 ], 81 "changes": [ 82 { 83 "version": "v6.3.0", 84 "pr-url": "https://github.com/nodejs/node/pull/6635", 85 "description": "The `breakOnSigint` option is supported now." 86 } 87 ] 88 }, 89 "signatures": [ 90 { 91 "return": { 92 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 93 "name": "return", 94 "type": "any", 95 "desc": "the result of the very last statement executed in the script." 96 }, 97 "params": [ 98 { 99 "textRaw": "`contextifiedObject` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", 100 "name": "contextifiedObject", 101 "type": "Object", 102 "desc": "A [contextified][] object as returned by the `vm.createContext()` method." 103 }, 104 { 105 "textRaw": "`options` {Object}", 106 "name": "options", 107 "type": "Object", 108 "options": [ 109 { 110 "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", 111 "name": "displayErrors", 112 "type": "boolean", 113 "default": "`true`", 114 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 115 }, 116 { 117 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 118 "name": "timeout", 119 "type": "integer", 120 "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." 121 }, 122 { 123 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 124 "name": "breakOnSigint", 125 "type": "boolean", 126 "default": "`false`", 127 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 128 } 129 ] 130 } 131 ] 132 } 133 ], 134 "desc": "<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given\n<code>contextifiedObject</code> and returns the result. Running code does not have access\nto local scope.</p>\n<p>The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the <code>context</code> object.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nconst context = {\n animal: 'cat',\n count: 2,\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nvm.createContext(context);\nfor (let i = 0; i < 10; ++i) {\n script.runInContext(context);\n}\n\nconsole.log(context);\n// Prints: { animal: 'cat', count: 12, name: 'kitty' }\n</code></pre>\n<p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.</p>" 135 }, 136 { 137 "textRaw": "`script.runInNewContext([contextObject[, options]])`", 138 "type": "method", 139 "name": "runInNewContext", 140 "meta": { 141 "added": [ 142 "v0.3.1" 143 ], 144 "changes": [ 145 { 146 "version": "v14.6.0", 147 "pr-url": "https://github.com/nodejs/node/pull/34023", 148 "description": "The `microtaskMode` option is supported now." 149 }, 150 { 151 "version": "v10.0.0", 152 "pr-url": "https://github.com/nodejs/node/pull/19016", 153 "description": "The `contextCodeGeneration` option is supported now." 154 }, 155 { 156 "version": "v6.3.0", 157 "pr-url": "https://github.com/nodejs/node/pull/6635", 158 "description": "The `breakOnSigint` option is supported now." 159 } 160 ] 161 }, 162 "signatures": [ 163 { 164 "return": { 165 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 166 "name": "return", 167 "type": "any", 168 "desc": "the result of the very last statement executed in the script." 169 }, 170 "params": [ 171 { 172 "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", 173 "name": "contextObject", 174 "type": "Object", 175 "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." 176 }, 177 { 178 "textRaw": "`options` {Object}", 179 "name": "options", 180 "type": "Object", 181 "options": [ 182 { 183 "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", 184 "name": "displayErrors", 185 "type": "boolean", 186 "default": "`true`", 187 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 188 }, 189 { 190 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 191 "name": "timeout", 192 "type": "integer", 193 "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." 194 }, 195 { 196 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 197 "name": "breakOnSigint", 198 "type": "boolean", 199 "default": "`false`", 200 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 201 }, 202 { 203 "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", 204 "name": "contextName", 205 "type": "string", 206 "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", 207 "desc": "Human-readable name of the newly created context." 208 }, 209 { 210 "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", 211 "name": "contextOrigin", 212 "type": "string", 213 "default": "`''`", 214 "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." 215 }, 216 { 217 "textRaw": "`contextCodeGeneration` {Object}", 218 "name": "contextCodeGeneration", 219 "type": "Object", 220 "options": [ 221 { 222 "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", 223 "name": "strings", 224 "type": "boolean", 225 "default": "`true`", 226 "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." 227 }, 228 { 229 "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", 230 "name": "wasm", 231 "type": "boolean", 232 "default": "`true`", 233 "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." 234 } 235 ] 236 }, 237 { 238 "textRaw": "`microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case.", 239 "name": "microtaskMode", 240 "type": "string", 241 "desc": "If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case." 242 } 243 ] 244 } 245 ] 246 } 247 ], 248 "desc": "<p>First contextifies the given <code>contextObject</code>, runs the compiled code contained\nby the <code>vm.Script</code> object within the created context, and returns the result.\nRunning code does not have access to local scope.</p>\n<p>The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual <code>context</code>.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst contexts = [{}, {}, {}];\ncontexts.forEach((context) => {\n script.runInNewContext(context);\n});\n\nconsole.log(contexts);\n// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n</code></pre>" 249 }, 250 { 251 "textRaw": "`script.runInThisContext([options])`", 252 "type": "method", 253 "name": "runInThisContext", 254 "meta": { 255 "added": [ 256 "v0.3.1" 257 ], 258 "changes": [ 259 { 260 "version": "v6.3.0", 261 "pr-url": "https://github.com/nodejs/node/pull/6635", 262 "description": "The `breakOnSigint` option is supported now." 263 } 264 ] 265 }, 266 "signatures": [ 267 { 268 "return": { 269 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 270 "name": "return", 271 "type": "any", 272 "desc": "the result of the very last statement executed in the script." 273 }, 274 "params": [ 275 { 276 "textRaw": "`options` {Object}", 277 "name": "options", 278 "type": "Object", 279 "options": [ 280 { 281 "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", 282 "name": "displayErrors", 283 "type": "boolean", 284 "default": "`true`", 285 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 286 }, 287 { 288 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 289 "name": "timeout", 290 "type": "integer", 291 "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." 292 }, 293 { 294 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 295 "name": "breakOnSigint", 296 "type": "boolean", 297 "default": "`false`", 298 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 299 } 300 ] 301 } 302 ] 303 } 304 ], 305 "desc": "<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the\ncurrent <code>global</code> object. Running code does not have access to local scope, but\n<em>does</em> have access to the current <code>global</code> object.</p>\n<p>The following example compiles code that increments a <code>global</code> variable then\nexecutes that code multiple times:</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n</code></pre>" 306 } 307 ], 308 "signatures": [ 309 { 310 "params": [ 311 { 312 "textRaw": "`code` {string} The JavaScript code to compile.", 313 "name": "code", 314 "type": "string", 315 "desc": "The JavaScript code to compile." 316 }, 317 { 318 "textRaw": "`options` {Object|string}", 319 "name": "options", 320 "type": "Object|string", 321 "options": [ 322 { 323 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 324 "name": "filename", 325 "type": "string", 326 "default": "`'evalmachine.<anonymous>'`", 327 "desc": "Specifies the filename used in stack traces produced by this script." 328 }, 329 { 330 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 331 "name": "lineOffset", 332 "type": "number", 333 "default": "`0`", 334 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 335 }, 336 { 337 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 338 "name": "columnOffset", 339 "type": "number", 340 "default": "`0`", 341 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 342 }, 343 { 344 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", 345 "name": "cachedData", 346 "type": "Buffer|TypedArray|DataView", 347 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." 348 }, 349 { 350 "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", 351 "name": "produceCachedData", 352 "type": "boolean", 353 "default": "`false`", 354 "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." 355 }, 356 { 357 "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 358 "name": "importModuleDynamically", 359 "type": "Function", 360 "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 361 "options": [ 362 { 363 "textRaw": "`specifier` {string} specifier passed to `import()`", 364 "name": "specifier", 365 "type": "string", 366 "desc": "specifier passed to `import()`" 367 }, 368 { 369 "textRaw": "`script` {vm.Script}", 370 "name": "script", 371 "type": "vm.Script" 372 }, 373 { 374 "textRaw": "`importAttributes` {Object} The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided.", 375 "name": "importAttributes", 376 "type": "Object", 377 "desc": "The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided." 378 }, 379 { 380 "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", 381 "name": "return", 382 "type": "Module Namespace Object|vm.Module", 383 "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." 384 } 385 ] 386 } 387 ] 388 } 389 ], 390 "desc": "<p>If <code>options</code> is a string, then it specifies the filename.</p>\n<p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The\ncompiled <code>vm.Script</code> can be run later multiple times. The <code>code</code> is not bound to\nany global object; rather, it is bound before each run, just for that run.</p>" 391 } 392 ] 393 }, 394 { 395 "textRaw": "Class: `vm.Module`", 396 "type": "class", 397 "name": "vm.Module", 398 "meta": { 399 "added": [ 400 "v13.0.0", 401 "v12.16.0" 402 ], 403 "changes": [] 404 }, 405 "stability": 1, 406 "stabilityText": "Experimental", 407 "desc": "<p>This feature is only available with the <code>--experimental-vm-modules</code> command\nflag enabled.</p>\n<p>The <code>vm.Module</code> class provides a low-level interface for using\nECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code>\nclass that closely mirrors <a href=\"https://www.ecma-international.org/ecma-262/#sec-abstract-module-records\">Module Record</a>s as defined in the ECMAScript\nspecification.</p>\n<p>Unlike <code>vm.Script</code> however, every <code>vm.Module</code> object is bound to a context from\nits creation. Operations on <code>vm.Module</code> objects are intrinsically asynchronous,\nin contrast with the synchronous nature of <code>vm.Script</code> objects. The use of\n'async' functions can help with manipulating <code>vm.Module</code> objects.</p>\n<p>Using a <code>vm.Module</code> object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.</p>\n<p>This implementation lies at a lower level than the <a href=\"esm.html#modules-ecmascript-modules\">ECMAScript Module\nloader</a>. There is also no way to interact with the Loader yet, though\nsupport is planned.</p>\n<pre><code class=\"language-mjs\">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 bar = new vm.SourceTextModule(`\n import s from 'foo';\n s;\n print(s);\n`, { context: contextifiedObject });\n\n// Step 2\n//\n// \"Link\" the imported dependencies of this Module to it.\n//\n// The provided linking callback (the \"linker\") accepts two arguments: the\n// parent module (`bar` in this case) and the string that is the specifier of\n// the imported module. The callback is expected to return a Module that\n// corresponds to the provided specifier, with certain requirements documented\n// in `module.link()`.\n//\n// If linking has not started for the returned Module, the same linker\n// callback will be called on the returned Module.\n//\n// Even top-level Modules without dependencies must be explicitly linked. The\n// callback provided would never be called, however.\n//\n// The link() method returns a Promise that will be resolved when all the\n// Promises returned by the linker resolve.\n//\n// Note: This is a contrived example in that the linker function creates a new\n// \"foo\" module every time it is called. In a full-fledged module system, a\n// cache would probably be used to avoid duplicated modules.\n\nasync function linker(specifier, referencingModule) {\n if (specifier === 'foo') {\n return new vm.SourceTextModule(`\n // The \"secret\" variable refers to the global variable we added to\n // \"contextifiedObject\" when creating the context.\n export default secret;\n `, { context: referencingModule.context });\n\n // Using `contextifiedObject` instead of `referencingModule.context`\n // here would work as well.\n }\n throw new Error(`Unable to resolve dependency: ${specifier}`);\n}\nawait bar.link(linker);\n\n// Step 3\n//\n// Evaluate the Module. The evaluate() method returns a promise which will\n// resolve after the module has finished evaluating.\n\n// Prints 42.\nawait bar.evaluate();\n</code></pre>\n<pre><code class=\"language-cjs\">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 bar = new vm.SourceTextModule(`\n import s from 'foo';\n s;\n print(s);\n `, { context: contextifiedObject });\n\n // Step 2\n //\n // \"Link\" the imported dependencies of this Module to it.\n //\n // The provided linking callback (the \"linker\") accepts two arguments: the\n // parent module (`bar` in this case) and the string that is the specifier of\n // the imported module. The callback is expected to return a Module that\n // corresponds to the provided specifier, with certain requirements documented\n // in `module.link()`.\n //\n // If linking has not started for the returned Module, the same linker\n // callback will be called on the returned Module.\n //\n // Even top-level Modules without dependencies must be explicitly linked. The\n // callback provided would never be called, however.\n //\n // The link() method returns a Promise that will be resolved when all the\n // Promises returned by the linker resolve.\n //\n // Note: This is a contrived example in that the linker function creates a new\n // \"foo\" module every time it is called. In a full-fledged module system, a\n // cache would probably be used to avoid duplicated modules.\n\n async function linker(specifier, referencingModule) {\n if (specifier === 'foo') {\n return new vm.SourceTextModule(`\n // The \"secret\" variable refers to the global variable we added to\n // \"contextifiedObject\" when creating the context.\n export default secret;\n `, { context: referencingModule.context });\n\n // Using `contextifiedObject` instead of `referencingModule.context`\n // here would work as well.\n }\n throw new Error(`Unable to resolve dependency: ${specifier}`);\n }\n await bar.link(linker);\n\n // Step 3\n //\n // Evaluate the Module. The evaluate() method returns a promise which will\n // resolve after the module has finished evaluating.\n\n // Prints 42.\n await bar.evaluate();\n})();\n</code></pre>", 408 "properties": [ 409 { 410 "textRaw": "`dependencySpecifiers` {string\\[]}", 411 "type": "string\\[]", 412 "name": "dependencySpecifiers", 413 "desc": "<p>The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.</p>\n<p>Corresponds to the <code>[[RequestedModules]]</code> field of <a href=\"https://tc39.es/ecma262/#sec-cyclic-module-records\">Cyclic Module Record</a>s in\nthe ECMAScript specification.</p>" 414 }, 415 { 416 "textRaw": "`error` {any}", 417 "type": "any", 418 "name": "error", 419 "desc": "<p>If the <code>module.status</code> is <code>'errored'</code>, 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.</p>\n<p>The value <code>undefined</code> cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with <code>throw undefined;</code>.</p>\n<p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href=\"https://tc39.es/ecma262/#sec-cyclic-module-records\">Cyclic Module Record</a>s\nin the ECMAScript specification.</p>" 420 }, 421 { 422 "textRaw": "`identifier` {string}", 423 "type": "string", 424 "name": "identifier", 425 "desc": "<p>The identifier of the current module, as set in the constructor.</p>" 426 }, 427 { 428 "textRaw": "`namespace` {Object}", 429 "type": "Object", 430 "name": "namespace", 431 "desc": "<p>The namespace object of the module. This is only available after linking\n(<code>module.link()</code>) has completed.</p>\n<p>Corresponds to the <a href=\"https://tc39.es/ecma262/#sec-getmodulenamespace\">GetModuleNamespace</a> abstract operation in the ECMAScript\nspecification.</p>" 432 }, 433 { 434 "textRaw": "`status` {string}", 435 "type": "string", 436 "name": "status", 437 "desc": "<p>The current status of the module. Will be one of:</p>\n<ul>\n<li>\n<p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p>\n</li>\n<li>\n<p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned\nby the linker function have been resolved yet.</p>\n</li>\n<li>\n<p><code>'linked'</code>: The module has been linked successfully, and all of its\ndependencies are linked, but <code>module.evaluate()</code> has not yet been called.</p>\n</li>\n<li>\n<p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on\nitself or a parent module.</p>\n</li>\n<li>\n<p><code>'evaluated'</code>: The module has been successfully evaluated.</p>\n</li>\n<li>\n<p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p>\n</li>\n</ul>\n<p>Other than <code>'errored'</code>, this status string corresponds to the specification's\n<a href=\"https://tc39.es/ecma262/#sec-cyclic-module-records\">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to\n<code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a\nvalue that is not <code>undefined</code>.</p>" 438 } 439 ], 440 "methods": [ 441 { 442 "textRaw": "`module.evaluate([options])`", 443 "type": "method", 444 "name": "evaluate", 445 "signatures": [ 446 { 447 "return": { 448 "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", 449 "name": "return", 450 "type": "Promise", 451 "desc": "Fulfills with `undefined` upon success." 452 }, 453 "params": [ 454 { 455 "textRaw": "`options` {Object}", 456 "name": "options", 457 "type": "Object", 458 "options": [ 459 { 460 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 461 "name": "timeout", 462 "type": "integer", 463 "desc": "Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer." 464 }, 465 { 466 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 467 "name": "breakOnSigint", 468 "type": "boolean", 469 "default": "`false`", 470 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 471 } 472 ] 473 } 474 ] 475 } 476 ], 477 "desc": "<p>Evaluate the module.</p>\n<p>This must be called after the module has been linked; otherwise it will reject.\nIt could be called also when the module has already been evaluated, in which\ncase it will either do nothing if the initial evaluation ended in success\n(<code>module.status</code> is <code>'evaluated'</code>) or it will re-throw the exception that the\ninitial evaluation resulted in (<code>module.status</code> is <code>'errored'</code>).</p>\n<p>This method cannot be called while the module is being evaluated\n(<code>module.status</code> is <code>'evaluating'</code>).</p>\n<p>Corresponds to the <a href=\"https://tc39.es/ecma262/#sec-moduleevaluation\">Evaluate() concrete method</a> field of <a href=\"https://tc39.es/ecma262/#sec-cyclic-module-records\">Cyclic Module\nRecord</a>s in the ECMAScript specification.</p>" 478 }, 479 { 480 "textRaw": "`module.link(linker)`", 481 "type": "method", 482 "name": "link", 483 "meta": { 484 "changes": [ 485 { 486 "version": "v18.19.0", 487 "pr-url": "https://github.com/nodejs/node/pull/50141", 488 "description": "The option `extra.assert` is renamed to `extra.attributes`. The former name is still provided for backward compatibility." 489 } 490 ] 491 }, 492 "signatures": [ 493 { 494 "return": { 495 "textRaw": "Returns: {Promise}", 496 "name": "return", 497 "type": "Promise" 498 }, 499 "params": [ 500 { 501 "textRaw": "`linker` {Function}", 502 "name": "linker", 503 "type": "Function", 504 "options": [ 505 { 506 "textRaw": "`specifier` {string} The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```", 507 "name": "specifier", 508 "type": "string", 509 "desc": "The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```" 510 }, 511 { 512 "textRaw": "`referencingModule` {vm.Module} The `Module` object `link()` is called on.", 513 "name": "referencingModule", 514 "type": "vm.Module", 515 "desc": "The `Module` object `link()` is called on." 516 }, 517 { 518 "textRaw": "`extra` {Object}", 519 "name": "extra", 520 "type": "Object", 521 "options": [ 522 { 523 "textRaw": "`attributes` {Object} The data from the attribute:```mjs import foo from 'foo' with { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the attribute ```Per ECMA-262, hosts are expected to trigger an error if an unsupported attribute is present.", 524 "name": "attributes", 525 "type": "Object", 526 "desc": "The data from the attribute:```mjs import foo from 'foo' with { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the attribute ```Per ECMA-262, hosts are expected to trigger an error if an unsupported attribute is present." 527 }, 528 { 529 "textRaw": "`assert` {Object} Alias for `extra.attributes`.", 530 "name": "assert", 531 "type": "Object", 532 "desc": "Alias for `extra.attributes`." 533 } 534 ] 535 }, 536 { 537 "textRaw": "Returns: {vm.Module|Promise}", 538 "name": "return", 539 "type": "vm.Module|Promise" 540 } 541 ] 542 } 543 ] 544 } 545 ], 546 "desc": "<p>Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.</p>\n<p>The function is expected to return a <code>Module</code> object or a <code>Promise</code> that\neventually resolves to a <code>Module</code> object. The returned <code>Module</code> must satisfy the\nfollowing two invariants:</p>\n<ul>\n<li>It must belong to the same context as the parent <code>Module</code>.</li>\n<li>Its <code>status</code> must not be <code>'errored'</code>.</li>\n</ul>\n<p>If the returned <code>Module</code>'s <code>status</code> is <code>'unlinked'</code>, this method will be\nrecursively called on the returned <code>Module</code> with the same provided <code>linker</code>\nfunction.</p>\n<p><code>link()</code> returns a <code>Promise</code> that will either get resolved when all linking\ninstances resolve to a valid <code>Module</code>, or rejected if the linker function either\nthrows an exception or returns an invalid <code>Module</code>.</p>\n<p>The linker function roughly corresponds to the implementation-defined\n<a href=\"https://tc39.es/ecma262/#sec-hostresolveimportedmodule\">HostResolveImportedModule</a> abstract operation in the ECMAScript\nspecification, with a few key differences:</p>\n<ul>\n<li>The linker function is allowed to be asynchronous while\n<a href=\"https://tc39.es/ecma262/#sec-hostresolveimportedmodule\">HostResolveImportedModule</a> is synchronous.</li>\n</ul>\n<p>The actual <a href=\"https://tc39.es/ecma262/#sec-hostresolveimportedmodule\">HostResolveImportedModule</a> 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<a href=\"https://tc39.es/ecma262/#sec-hostresolveimportedmodule\">HostResolveImportedModule</a> implementation is fully synchronous per\nspecification.</p>\n<p>Corresponds to the <a href=\"https://tc39.es/ecma262/#sec-moduledeclarationlinking\">Link() concrete method</a> field of <a href=\"https://tc39.es/ecma262/#sec-cyclic-module-records\">Cyclic Module\nRecord</a>s in the ECMAScript specification.</p>" 547 } 548 ] 549 }, 550 { 551 "textRaw": "Class: `vm.SourceTextModule`", 552 "type": "class", 553 "name": "vm.SourceTextModule", 554 "meta": { 555 "added": [ 556 "v9.6.0" 557 ], 558 "changes": [] 559 }, 560 "stability": 1, 561 "stabilityText": "Experimental", 562 "desc": "<p>This feature is only available with the <code>--experimental-vm-modules</code> command\nflag enabled.</p>\n<ul>\n<li>Extends: <a href=\"vm.html#class-vmmodule\" class=\"type\"><vm.Module></a></li>\n</ul>\n<p>The <code>vm.SourceTextModule</code> class provides the <a href=\"https://tc39.es/ecma262/#sec-source-text-module-records\">Source Text Module Record</a> as\ndefined in the ECMAScript specification.</p>", 563 "methods": [ 564 { 565 "textRaw": "`sourceTextModule.createCachedData()`", 566 "type": "method", 567 "name": "createCachedData", 568 "meta": { 569 "added": [ 570 "v13.7.0", 571 "v12.17.0" 572 ], 573 "changes": [] 574 }, 575 "signatures": [ 576 { 577 "return": { 578 "textRaw": "Returns: {Buffer}", 579 "name": "return", 580 "type": "Buffer" 581 }, 582 "params": [] 583 } 584 ], 585 "desc": "<p>Creates a code cache that can be used with the <code>SourceTextModule</code> constructor's\n<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called any number\nof times before the module has been evaluated.</p>\n<p>The code cache of the <code>SourceTextModule</code> 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 <code>SourceTextModule</code> instances multiple times.</p>\n<p>Functions in the <code>SourceTextModule</code> source can be marked as lazily compiled\nand they are not compiled at construction of the <code>SourceTextModule</code>. 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<code>SourceTextModule</code> that it can use to speed up future compilations.</p>\n<pre><code class=\"language-js\">// 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</code></pre>" 586 } 587 ], 588 "signatures": [ 589 { 590 "params": [ 591 { 592 "textRaw": "`code` {string} JavaScript Module code to parse", 593 "name": "code", 594 "type": "string", 595 "desc": "JavaScript Module code to parse" 596 }, 597 { 598 "textRaw": "`options`", 599 "name": "options", 600 "options": [ 601 { 602 "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", 603 "name": "identifier", 604 "type": "string", 605 "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", 606 "desc": "String used in stack traces." 607 }, 608 { 609 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created.", 610 "name": "cachedData", 611 "type": "Buffer|TypedArray|DataView", 612 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created." 613 }, 614 { 615 "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in. If no context is specified, the module is evaluated in the current execution context.", 616 "name": "context", 617 "type": "Object", 618 "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in. If no context is specified, the module is evaluated in the current execution context." 619 }, 620 { 621 "textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", 622 "name": "lineOffset", 623 "type": "integer", 624 "default": "`0`", 625 "desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`." 626 }, 627 { 628 "textRaw": "`columnOffset` {integer} Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", 629 "name": "columnOffset", 630 "type": "integer", 631 "default": "`0`", 632 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`." 633 }, 634 { 635 "textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.", 636 "name": "initializeImportMeta", 637 "type": "Function", 638 "desc": "Called during evaluation of this `Module` to initialize the `import.meta`.", 639 "options": [ 640 { 641 "textRaw": "`meta` {import.meta}", 642 "name": "meta", 643 "type": "import.meta" 644 }, 645 { 646 "textRaw": "`module` {vm.SourceTextModule}", 647 "name": "module", 648 "type": "vm.SourceTextModule" 649 } 650 ] 651 }, 652 { 653 "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 654 "name": "importModuleDynamically", 655 "type": "Function", 656 "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 657 "options": [ 658 { 659 "textRaw": "`specifier` {string} specifier passed to `import()`", 660 "name": "specifier", 661 "type": "string", 662 "desc": "specifier passed to `import()`" 663 }, 664 { 665 "textRaw": "`module` {vm.Module}", 666 "name": "module", 667 "type": "vm.Module" 668 }, 669 { 670 "textRaw": "`importAttributes` {Object} The `\"assert\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided.", 671 "name": "importAttributes", 672 "type": "Object", 673 "desc": "The `\"assert\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided." 674 }, 675 { 676 "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", 677 "name": "return", 678 "type": "Module Namespace Object|vm.Module", 679 "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." 680 } 681 ] 682 } 683 ] 684 } 685 ], 686 "desc": "<p>Creates a new <code>SourceTextModule</code> instance.</p>\n<p>Properties assigned to the <code>import.meta</code> object that are objects may\nallow the module to access information outside the specified <code>context</code>. Use\n<code>vm.runInContext()</code> to create objects in a specific context.</p>\n<pre><code class=\"language-mjs\">import vm from 'node:vm';\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\nconst module = new vm.SourceTextModule(\n 'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n {\n initializeImportMeta(meta) {\n // Note: this object is created in the top context. As such,\n // Object.getPrototypeOf(import.meta.prop) points to the\n // Object.prototype in the top context rather than that in\n // the contextified object.\n meta.prop = {};\n },\n });\n// Since module has no dependencies, the linker function will never be called.\nawait module.link(() => {});\nawait module.evaluate();\n\n// Now, Object.prototype.secret will be equal to 42.\n//\n// To fix this problem, replace\n// meta.prop = {};\n// above with\n// meta.prop = vm.runInContext('{}', contextifiedObject);\n</code></pre>\n<pre><code class=\"language-cjs\">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 initializeImportMeta(meta) {\n // Note: this object is created in the top context. As such,\n // Object.getPrototypeOf(import.meta.prop) points to the\n // Object.prototype in the top context rather than that in\n // the contextified object.\n meta.prop = {};\n },\n });\n // Since module has no dependencies, the linker function will never be called.\n await module.link(() => {});\n await module.evaluate();\n // Now, Object.prototype.secret will be equal to 42.\n //\n // To fix this problem, replace\n // meta.prop = {};\n // above with\n // meta.prop = vm.runInContext('{}', contextifiedObject);\n})();\n</code></pre>" 687 } 688 ] 689 }, 690 { 691 "textRaw": "Class: `vm.SyntheticModule`", 692 "type": "class", 693 "name": "vm.SyntheticModule", 694 "meta": { 695 "added": [ 696 "v13.0.0", 697 "v12.16.0" 698 ], 699 "changes": [] 700 }, 701 "stability": 1, 702 "stabilityText": "Experimental", 703 "desc": "<p>This feature is only available with the <code>--experimental-vm-modules</code> command\nflag enabled.</p>\n<ul>\n<li>Extends: <a href=\"vm.html#class-vmmodule\" class=\"type\"><vm.Module></a></li>\n</ul>\n<p>The <code>vm.SyntheticModule</code> class provides the <a href=\"https://heycam.github.io/webidl/#synthetic-module-records\">Synthetic Module Record</a> 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.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nconst source = '{ \"a\": 1 }';\nconst module = new vm.SyntheticModule(['default'], function() {\n const obj = JSON.parse(source);\n this.setExport('default', obj);\n});\n\n// Use `module` in linking...\n</code></pre>", 704 "methods": [ 705 { 706 "textRaw": "`syntheticModule.setExport(name, value)`", 707 "type": "method", 708 "name": "setExport", 709 "meta": { 710 "added": [ 711 "v13.0.0", 712 "v12.16.0" 713 ], 714 "changes": [] 715 }, 716 "signatures": [ 717 { 718 "params": [ 719 { 720 "textRaw": "`name` {string} Name of the export to set.", 721 "name": "name", 722 "type": "string", 723 "desc": "Name of the export to set." 724 }, 725 { 726 "textRaw": "`value` {any} The value to set the export to.", 727 "name": "value", 728 "type": "any", 729 "desc": "The value to set the export to." 730 } 731 ] 732 } 733 ], 734 "desc": "<p>This method is used after the module is linked to set the values of exports. If\nit is called before the module is linked, an <a href=\"errors.html#err_vm_module_status\"><code>ERR_VM_MODULE_STATUS</code></a> error\nwill be thrown.</p>\n<pre><code class=\"language-mjs\">import vm from 'node:vm';\n\nconst m = new vm.SyntheticModule(['x'], () => {\n m.setExport('x', 1);\n});\n\nawait m.link(() => {});\nawait m.evaluate();\n\nassert.strictEqual(m.namespace.x, 1);\n</code></pre>\n<pre><code class=\"language-cjs\">const vm = require('node:vm');\n(async () => {\n const m = new vm.SyntheticModule(['x'], () => {\n m.setExport('x', 1);\n });\n await m.link(() => {});\n await m.evaluate();\n assert.strictEqual(m.namespace.x, 1);\n})();\n</code></pre>" 735 } 736 ], 737 "signatures": [ 738 { 739 "params": [ 740 { 741 "textRaw": "`exportNames` {string\\[]} Array of names that will be exported from the module.", 742 "name": "exportNames", 743 "type": "string\\[]", 744 "desc": "Array of names that will be exported from the module." 745 }, 746 { 747 "textRaw": "`evaluateCallback` {Function} Called when the module is evaluated.", 748 "name": "evaluateCallback", 749 "type": "Function", 750 "desc": "Called when the module is evaluated." 751 }, 752 { 753 "textRaw": "`options`", 754 "name": "options", 755 "options": [ 756 { 757 "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", 758 "name": "identifier", 759 "type": "string", 760 "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", 761 "desc": "String used in stack traces." 762 }, 763 { 764 "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", 765 "name": "context", 766 "type": "Object", 767 "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." 768 } 769 ] 770 } 771 ], 772 "desc": "<p>Creates a new <code>SyntheticModule</code> instance.</p>\n<p>Objects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified <code>context</code>. Use\n<code>vm.runInContext()</code> to create objects in a specific context.</p>" 773 } 774 ] 775 } 776 ], 777 "methods": [ 778 { 779 "textRaw": "`vm.compileFunction(code[, params[, options]])`", 780 "type": "method", 781 "name": "compileFunction", 782 "meta": { 783 "added": [ 784 "v10.10.0" 785 ], 786 "changes": [ 787 { 788 "version": [ 789 "v18.15.0" 790 ], 791 "pr-url": "https://github.com/nodejs/node/pull/46320", 792 "description": "The return value now includes `cachedDataRejected` with the same semantics as the `vm.Script` version if the `cachedData` option was passed." 793 }, 794 { 795 "version": [ 796 "v17.0.0", 797 "v16.12.0" 798 ], 799 "pr-url": "https://github.com/nodejs/node/pull/40249", 800 "description": "Added support for import attributes to the `importModuleDynamically` parameter." 801 }, 802 { 803 "version": "v15.9.0", 804 "pr-url": "https://github.com/nodejs/node/pull/35431", 805 "description": "Added `importModuleDynamically` option again." 806 }, 807 { 808 "version": "v14.3.0", 809 "pr-url": "https://github.com/nodejs/node/pull/33364", 810 "description": "Removal of `importModuleDynamically` due to compatibility issues." 811 }, 812 { 813 "version": [ 814 "v14.1.0", 815 "v13.14.0" 816 ], 817 "pr-url": "https://github.com/nodejs/node/pull/32985", 818 "description": "The `importModuleDynamically` option is now supported." 819 } 820 ] 821 }, 822 "signatures": [ 823 { 824 "return": { 825 "textRaw": "Returns: {Function}", 826 "name": "return", 827 "type": "Function" 828 }, 829 "params": [ 830 { 831 "textRaw": "`code` {string} The body of the function to compile.", 832 "name": "code", 833 "type": "string", 834 "desc": "The body of the function to compile." 835 }, 836 { 837 "textRaw": "`params` {string\\[]} An array of strings containing all parameters for the function.", 838 "name": "params", 839 "type": "string\\[]", 840 "desc": "An array of strings containing all parameters for the function." 841 }, 842 { 843 "textRaw": "`options` {Object}", 844 "name": "options", 845 "type": "Object", 846 "options": [ 847 { 848 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `''`.", 849 "name": "filename", 850 "type": "string", 851 "default": "`''`", 852 "desc": "Specifies the filename used in stack traces produced by this script." 853 }, 854 { 855 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 856 "name": "lineOffset", 857 "type": "number", 858 "default": "`0`", 859 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 860 }, 861 { 862 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 863 "name": "columnOffset", 864 "type": "number", 865 "default": "`0`", 866 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 867 }, 868 { 869 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. This must be produced by a prior call to [`vm.compileFunction()`][] with the same `code` and `params`.", 870 "name": "cachedData", 871 "type": "Buffer|TypedArray|DataView", 872 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. This must be produced by a prior call to [`vm.compileFunction()`][] with the same `code` and `params`." 873 }, 874 { 875 "textRaw": "`produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`.", 876 "name": "produceCachedData", 877 "type": "boolean", 878 "default": "`false`", 879 "desc": "Specifies whether to produce new cache data." 880 }, 881 { 882 "textRaw": "`parsingContext` {Object} The [contextified][] object in which the said function should be compiled in.", 883 "name": "parsingContext", 884 "type": "Object", 885 "desc": "The [contextified][] object in which the said function should be compiled in." 886 }, 887 { 888 "textRaw": "`contextExtensions` {Object\\[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`.", 889 "name": "contextExtensions", 890 "type": "Object\\[]", 891 "default": "`[]`", 892 "desc": "An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling." 893 }, 894 { 895 "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 896 "name": "importModuleDynamically", 897 "type": "Function", 898 "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 899 "options": [ 900 { 901 "textRaw": "`specifier` {string} specifier passed to `import()`", 902 "name": "specifier", 903 "type": "string", 904 "desc": "specifier passed to `import()`" 905 }, 906 { 907 "textRaw": "`function` {Function}", 908 "name": "function", 909 "type": "Function" 910 }, 911 { 912 "textRaw": "`importAttributes` {Object} The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided.", 913 "name": "importAttributes", 914 "type": "Object", 915 "desc": "The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided." 916 }, 917 { 918 "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", 919 "name": "return", 920 "type": "Module Namespace Object|vm.Module", 921 "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." 922 } 923 ] 924 } 925 ] 926 } 927 ] 928 } 929 ], 930 "desc": "<p>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 <code>params</code>.</p>" 931 }, 932 { 933 "textRaw": "`vm.createContext([contextObject[, options]])`", 934 "type": "method", 935 "name": "createContext", 936 "meta": { 937 "added": [ 938 "v0.3.1" 939 ], 940 "changes": [ 941 { 942 "version": "v14.6.0", 943 "pr-url": "https://github.com/nodejs/node/pull/34023", 944 "description": "The `microtaskMode` option is supported now." 945 }, 946 { 947 "version": "v10.0.0", 948 "pr-url": "https://github.com/nodejs/node/pull/19398", 949 "description": "The first argument can no longer be a function." 950 }, 951 { 952 "version": "v10.0.0", 953 "pr-url": "https://github.com/nodejs/node/pull/19016", 954 "description": "The `codeGeneration` option is supported now." 955 } 956 ] 957 }, 958 "signatures": [ 959 { 960 "return": { 961 "textRaw": "Returns: {Object} contextified object.", 962 "name": "return", 963 "type": "Object", 964 "desc": "contextified object." 965 }, 966 "params": [ 967 { 968 "textRaw": "`contextObject` {Object}", 969 "name": "contextObject", 970 "type": "Object" 971 }, 972 { 973 "textRaw": "`options` {Object}", 974 "name": "options", 975 "type": "Object", 976 "options": [ 977 { 978 "textRaw": "`name` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", 979 "name": "name", 980 "type": "string", 981 "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", 982 "desc": "Human-readable name of the newly created context." 983 }, 984 { 985 "textRaw": "`origin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", 986 "name": "origin", 987 "type": "string", 988 "default": "`''`", 989 "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." 990 }, 991 { 992 "textRaw": "`codeGeneration` {Object}", 993 "name": "codeGeneration", 994 "type": "Object", 995 "options": [ 996 { 997 "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", 998 "name": "strings", 999 "type": "boolean", 1000 "default": "`true`", 1001 "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." 1002 }, 1003 { 1004 "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", 1005 "name": "wasm", 1006 "type": "boolean", 1007 "default": "`true`", 1008 "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." 1009 } 1010 ] 1011 }, 1012 { 1013 "textRaw": "`microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after a script has run through [`script.runInContext()`][]. They are included in the `timeout` and `breakOnSigint` scopes in that case.", 1014 "name": "microtaskMode", 1015 "type": "string", 1016 "desc": "If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after a script has run through [`script.runInContext()`][]. They are included in the `timeout` and `breakOnSigint` scopes in that case." 1017 } 1018 ] 1019 } 1020 ] 1021 } 1022 ], 1023 "desc": "<p>If given a <code>contextObject</code>, the <code>vm.createContext()</code> method will <a href=\"#what-does-it-mean-to-contextify-an-object\">prepare\nthat object</a> so that it can be used in calls to\n<a href=\"#vmrunincontextcode-contextifiedobject-options\"><code>vm.runInContext()</code></a> or <a href=\"#scriptrunincontextcontextifiedobject-options\"><code>script.runInContext()</code></a>. Inside such scripts,\nthe <code>contextObject</code> will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\n<a href=\"https://es5.github.io/#x15.1\">global object</a> has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\nvm.createContext(context);\n\nvm.runInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n</code></pre>\n<p>If <code>contextObject</code> is omitted (or passed explicitly as <code>undefined</code>), a new,\nempty <a href=\"#what-does-it-mean-to-contextify-an-object\">contextified</a> object will be returned.</p>\n<p>The <code>vm.createContext()</code> 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 <code><script></code> tags together within that\ncontext.</p>\n<p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the\nInspector API.</p>" 1024 }, 1025 { 1026 "textRaw": "`vm.isContext(object)`", 1027 "type": "method", 1028 "name": "isContext", 1029 "meta": { 1030 "added": [ 1031 "v0.11.7" 1032 ], 1033 "changes": [] 1034 }, 1035 "signatures": [ 1036 { 1037 "return": { 1038 "textRaw": "Returns: {boolean}", 1039 "name": "return", 1040 "type": "boolean" 1041 }, 1042 "params": [ 1043 { 1044 "textRaw": "`object` {Object}", 1045 "name": "object", 1046 "type": "Object" 1047 } 1048 ] 1049 } 1050 ], 1051 "desc": "<p>Returns <code>true</code> if the given <code>object</code> object has been <a href=\"#what-does-it-mean-to-contextify-an-object\">contextified</a> using\n<a href=\"#vmcreatecontextcontextobject-options\"><code>vm.createContext()</code></a>.</p>" 1052 }, 1053 { 1054 "textRaw": "`vm.measureMemory([options])`", 1055 "type": "method", 1056 "name": "measureMemory", 1057 "meta": { 1058 "added": [ 1059 "v13.10.0" 1060 ], 1061 "changes": [] 1062 }, 1063 "stability": 1, 1064 "stabilityText": "Experimental", 1065 "signatures": [ 1066 { 1067 "params": [] 1068 } 1069 ], 1070 "desc": "<p>Measure the memory known to V8 and used by all contexts known to the\ncurrent V8 isolate, or the main context.</p>\n<ul>\n<li><code>options</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\"><Object></a> Optional.\n<ul>\n<li><code>mode</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> Either <code>'summary'</code> or <code>'detailed'</code>. 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.\n<strong>Default:</strong> <code>'summary'</code></li>\n<li><code>execution</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> Either <code>'default'</code> or <code>'eager'</code>. 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.\n<strong>Default:</strong> <code>'default'</code></li>\n</ul>\n</li>\n<li>Returns: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" class=\"type\"><Promise></a> 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 <code>ERR_CONTEXT_NOT_INITIALIZED</code> error.</li>\n</ul>\n<p>The format of the object that the returned Promise may resolve with is\nspecific to the V8 engine and may change from one version of V8 to the next.</p>\n<p>The returned result is different from the statistics returned by\n<code>v8.getHeapSpaceStatistics()</code> in that <code>vm.measureMemory()</code> measure the\nmemory reachable by each V8 specific contexts in the current instance of\nthe V8 engine, while the result of <code>v8.getHeapSpaceStatistics()</code> measure\nthe memory occupied by each heap space in the current V8 instance.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n// Measure the memory used by the main context.\nvm.measureMemory({ mode: 'summary' })\n // This is the same as vm.measureMemory()\n .then((result) => {\n // The current format is:\n // {\n // total: {\n // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]\n // }\n // }\n console.log(result);\n });\n\nconst context = vm.createContext({ a: 1 });\nvm.measureMemory({ mode: 'detailed', execution: 'eager' })\n .then((result) => {\n // Reference the context here so that it won't be GC'ed\n // until the measurement is complete.\n console.log(context.a);\n // {\n // total: {\n // jsMemoryEstimate: 2574732,\n // jsMemoryRange: [ 2574732, 2904372 ]\n // },\n // current: {\n // jsMemoryEstimate: 2438996,\n // jsMemoryRange: [ 2438996, 2768636 ]\n // },\n // other: [\n // {\n // jsMemoryEstimate: 135736,\n // jsMemoryRange: [ 135736, 465376 ]\n // }\n // ]\n // }\n console.log(result);\n });\n</code></pre>" 1071 }, 1072 { 1073 "textRaw": "`vm.runInContext(code, contextifiedObject[, options])`", 1074 "type": "method", 1075 "name": "runInContext", 1076 "meta": { 1077 "added": [ 1078 "v0.3.1" 1079 ], 1080 "changes": [ 1081 { 1082 "version": [ 1083 "v17.0.0", 1084 "v16.12.0" 1085 ], 1086 "pr-url": "https://github.com/nodejs/node/pull/40249", 1087 "description": "Added support for import attributes to the `importModuleDynamically` parameter." 1088 }, 1089 { 1090 "version": "v6.3.0", 1091 "pr-url": "https://github.com/nodejs/node/pull/6635", 1092 "description": "The `breakOnSigint` option is supported now." 1093 } 1094 ] 1095 }, 1096 "signatures": [ 1097 { 1098 "return": { 1099 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 1100 "name": "return", 1101 "type": "any", 1102 "desc": "the result of the very last statement executed in the script." 1103 }, 1104 "params": [ 1105 { 1106 "textRaw": "`code` {string} The JavaScript code to compile and run.", 1107 "name": "code", 1108 "type": "string", 1109 "desc": "The JavaScript code to compile and run." 1110 }, 1111 { 1112 "textRaw": "`contextifiedObject` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.", 1113 "name": "contextifiedObject", 1114 "type": "Object", 1115 "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." 1116 }, 1117 { 1118 "textRaw": "`options` {Object|string}", 1119 "name": "options", 1120 "type": "Object|string", 1121 "options": [ 1122 { 1123 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 1124 "name": "filename", 1125 "type": "string", 1126 "default": "`'evalmachine.<anonymous>'`", 1127 "desc": "Specifies the filename used in stack traces produced by this script." 1128 }, 1129 { 1130 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1131 "name": "lineOffset", 1132 "type": "number", 1133 "default": "`0`", 1134 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 1135 }, 1136 { 1137 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1138 "name": "columnOffset", 1139 "type": "number", 1140 "default": "`0`", 1141 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 1142 }, 1143 { 1144 "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", 1145 "name": "displayErrors", 1146 "type": "boolean", 1147 "default": "`true`", 1148 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 1149 }, 1150 { 1151 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 1152 "name": "timeout", 1153 "type": "integer", 1154 "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." 1155 }, 1156 { 1157 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 1158 "name": "breakOnSigint", 1159 "type": "boolean", 1160 "default": "`false`", 1161 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 1162 }, 1163 { 1164 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", 1165 "name": "cachedData", 1166 "type": "Buffer|TypedArray|DataView", 1167 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." 1168 }, 1169 { 1170 "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 1171 "name": "importModuleDynamically", 1172 "type": "Function", 1173 "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 1174 "options": [ 1175 { 1176 "textRaw": "`specifier` {string} specifier passed to `import()`", 1177 "name": "specifier", 1178 "type": "string", 1179 "desc": "specifier passed to `import()`" 1180 }, 1181 { 1182 "textRaw": "`script` {vm.Script}", 1183 "name": "script", 1184 "type": "vm.Script" 1185 }, 1186 { 1187 "textRaw": "`importAttributes` {Object} The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided.", 1188 "name": "importAttributes", 1189 "type": "Object", 1190 "desc": "The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided." 1191 }, 1192 { 1193 "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", 1194 "name": "return", 1195 "type": "Module Namespace Object|vm.Module", 1196 "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." 1197 } 1198 ] 1199 } 1200 ] 1201 } 1202 ] 1203 } 1204 ], 1205 "desc": "<p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of\nthe <code>contextifiedObject</code>, then returns the result. Running code does not have\naccess to the local scope. The <code>contextifiedObject</code> object <em>must</em> have been\npreviously <a href=\"#what-does-it-mean-to-contextify-an-object\">contextified</a> using the <a href=\"#vmcreatecontextcontextobject-options\"><code>vm.createContext()</code></a> method.</p>\n<p>If <code>options</code> is a string, then it specifies the filename.</p>\n<p>The following example compiles and executes different scripts using a single\n<a href=\"#what-does-it-mean-to-contextify-an-object\">contextified</a> object:</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nconst contextObject = { globalVar: 1 };\nvm.createContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n vm.runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n</code></pre>" 1206 }, 1207 { 1208 "textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`", 1209 "type": "method", 1210 "name": "runInNewContext", 1211 "meta": { 1212 "added": [ 1213 "v0.3.1" 1214 ], 1215 "changes": [ 1216 { 1217 "version": [ 1218 "v17.0.0", 1219 "v16.12.0" 1220 ], 1221 "pr-url": "https://github.com/nodejs/node/pull/40249", 1222 "description": "Added support for import attributes to the `importModuleDynamically` parameter." 1223 }, 1224 { 1225 "version": "v14.6.0", 1226 "pr-url": "https://github.com/nodejs/node/pull/34023", 1227 "description": "The `microtaskMode` option is supported now." 1228 }, 1229 { 1230 "version": "v10.0.0", 1231 "pr-url": "https://github.com/nodejs/node/pull/19016", 1232 "description": "The `contextCodeGeneration` option is supported now." 1233 }, 1234 { 1235 "version": "v6.3.0", 1236 "pr-url": "https://github.com/nodejs/node/pull/6635", 1237 "description": "The `breakOnSigint` option is supported now." 1238 } 1239 ] 1240 }, 1241 "signatures": [ 1242 { 1243 "return": { 1244 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 1245 "name": "return", 1246 "type": "any", 1247 "desc": "the result of the very last statement executed in the script." 1248 }, 1249 "params": [ 1250 { 1251 "textRaw": "`code` {string} The JavaScript code to compile and run.", 1252 "name": "code", 1253 "type": "string", 1254 "desc": "The JavaScript code to compile and run." 1255 }, 1256 { 1257 "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", 1258 "name": "contextObject", 1259 "type": "Object", 1260 "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." 1261 }, 1262 { 1263 "textRaw": "`options` {Object|string}", 1264 "name": "options", 1265 "type": "Object|string", 1266 "options": [ 1267 { 1268 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 1269 "name": "filename", 1270 "type": "string", 1271 "default": "`'evalmachine.<anonymous>'`", 1272 "desc": "Specifies the filename used in stack traces produced by this script." 1273 }, 1274 { 1275 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1276 "name": "lineOffset", 1277 "type": "number", 1278 "default": "`0`", 1279 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 1280 }, 1281 { 1282 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1283 "name": "columnOffset", 1284 "type": "number", 1285 "default": "`0`", 1286 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 1287 }, 1288 { 1289 "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", 1290 "name": "displayErrors", 1291 "type": "boolean", 1292 "default": "`true`", 1293 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 1294 }, 1295 { 1296 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 1297 "name": "timeout", 1298 "type": "integer", 1299 "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." 1300 }, 1301 { 1302 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 1303 "name": "breakOnSigint", 1304 "type": "boolean", 1305 "default": "`false`", 1306 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 1307 }, 1308 { 1309 "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", 1310 "name": "contextName", 1311 "type": "string", 1312 "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", 1313 "desc": "Human-readable name of the newly created context." 1314 }, 1315 { 1316 "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", 1317 "name": "contextOrigin", 1318 "type": "string", 1319 "default": "`''`", 1320 "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." 1321 }, 1322 { 1323 "textRaw": "`contextCodeGeneration` {Object}", 1324 "name": "contextCodeGeneration", 1325 "type": "Object", 1326 "options": [ 1327 { 1328 "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", 1329 "name": "strings", 1330 "type": "boolean", 1331 "default": "`true`", 1332 "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." 1333 }, 1334 { 1335 "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", 1336 "name": "wasm", 1337 "type": "boolean", 1338 "default": "`true`", 1339 "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." 1340 } 1341 ] 1342 }, 1343 { 1344 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", 1345 "name": "cachedData", 1346 "type": "Buffer|TypedArray|DataView", 1347 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." 1348 }, 1349 { 1350 "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 1351 "name": "importModuleDynamically", 1352 "type": "Function", 1353 "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 1354 "options": [ 1355 { 1356 "textRaw": "`specifier` {string} specifier passed to `import()`", 1357 "name": "specifier", 1358 "type": "string", 1359 "desc": "specifier passed to `import()`" 1360 }, 1361 { 1362 "textRaw": "`script` {vm.Script}", 1363 "name": "script", 1364 "type": "vm.Script" 1365 }, 1366 { 1367 "textRaw": "`importAttributes` {Object} The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided.", 1368 "name": "importAttributes", 1369 "type": "Object", 1370 "desc": "The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided." 1371 }, 1372 { 1373 "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", 1374 "name": "return", 1375 "type": "Module Namespace Object|vm.Module", 1376 "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." 1377 } 1378 ] 1379 }, 1380 { 1381 "textRaw": "`microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case.", 1382 "name": "microtaskMode", 1383 "type": "string", 1384 "desc": "If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case." 1385 } 1386 ] 1387 } 1388 ] 1389 } 1390 ], 1391 "desc": "<p>The <code>vm.runInNewContext()</code> first contextifies the given <code>contextObject</code> (or\ncreates a new <code>contextObject</code> if passed as <code>undefined</code>), compiles the <code>code</code>,\nruns it within the created context, then returns the result. Running code\ndoes not have access to the local scope.</p>\n<p>If <code>options</code> is a string, then it specifies the filename.</p>\n<p>The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the <code>contextObject</code>.</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nconst contextObject = {\n animal: 'cat',\n count: 2,\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n</code></pre>" 1392 }, 1393 { 1394 "textRaw": "`vm.runInThisContext(code[, options])`", 1395 "type": "method", 1396 "name": "runInThisContext", 1397 "meta": { 1398 "added": [ 1399 "v0.3.1" 1400 ], 1401 "changes": [ 1402 { 1403 "version": [ 1404 "v17.0.0", 1405 "v16.12.0" 1406 ], 1407 "pr-url": "https://github.com/nodejs/node/pull/40249", 1408 "description": "Added support for import attributes to the `importModuleDynamically` parameter." 1409 }, 1410 { 1411 "version": "v6.3.0", 1412 "pr-url": "https://github.com/nodejs/node/pull/6635", 1413 "description": "The `breakOnSigint` option is supported now." 1414 } 1415 ] 1416 }, 1417 "signatures": [ 1418 { 1419 "return": { 1420 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 1421 "name": "return", 1422 "type": "any", 1423 "desc": "the result of the very last statement executed in the script." 1424 }, 1425 "params": [ 1426 { 1427 "textRaw": "`code` {string} The JavaScript code to compile and run.", 1428 "name": "code", 1429 "type": "string", 1430 "desc": "The JavaScript code to compile and run." 1431 }, 1432 { 1433 "textRaw": "`options` {Object|string}", 1434 "name": "options", 1435 "type": "Object|string", 1436 "options": [ 1437 { 1438 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 1439 "name": "filename", 1440 "type": "string", 1441 "default": "`'evalmachine.<anonymous>'`", 1442 "desc": "Specifies the filename used in stack traces produced by this script." 1443 }, 1444 { 1445 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1446 "name": "lineOffset", 1447 "type": "number", 1448 "default": "`0`", 1449 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 1450 }, 1451 { 1452 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1453 "name": "columnOffset", 1454 "type": "number", 1455 "default": "`0`", 1456 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 1457 }, 1458 { 1459 "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", 1460 "name": "displayErrors", 1461 "type": "boolean", 1462 "default": "`true`", 1463 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 1464 }, 1465 { 1466 "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", 1467 "name": "timeout", 1468 "type": "integer", 1469 "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." 1470 }, 1471 { 1472 "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", 1473 "name": "breakOnSigint", 1474 "type": "boolean", 1475 "default": "`false`", 1476 "desc": "If `true`, receiving `SIGINT` (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." 1477 }, 1478 { 1479 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", 1480 "name": "cachedData", 1481 "type": "Buffer|TypedArray|DataView", 1482 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." 1483 }, 1484 { 1485 "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 1486 "name": "importModuleDynamically", 1487 "type": "Function", 1488 "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment. If `--experimental-vm-modules` isn't set, this callback will be ignored and calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`][].", 1489 "options": [ 1490 { 1491 "textRaw": "`specifier` {string} specifier passed to `import()`", 1492 "name": "specifier", 1493 "type": "string", 1494 "desc": "specifier passed to `import()`" 1495 }, 1496 { 1497 "textRaw": "`script` {vm.Script}", 1498 "name": "script", 1499 "type": "vm.Script" 1500 }, 1501 { 1502 "textRaw": "`importAttributes` {Object} The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided.", 1503 "name": "importAttributes", 1504 "type": "Object", 1505 "desc": "The `\"with\"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided." 1506 }, 1507 { 1508 "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", 1509 "name": "return", 1510 "type": "Module Namespace Object|vm.Module", 1511 "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." 1512 } 1513 ] 1514 } 1515 ] 1516 } 1517 ] 1518 } 1519 ], 1520 "desc": "<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the\ncurrent <code>global</code> and returns the result. Running code does not have access to\nlocal scope, but does have access to the current <code>global</code> object.</p>\n<p>If <code>options</code> is a string, then it specifies the filename.</p>\n<p>The following example illustrates using both <code>vm.runInThisContext()</code> and\nthe JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\"><code>eval()</code></a> function to run the same code:</p>\n<!-- eslint-disable prefer-const -->\n<pre><code class=\"language-js\">const vm = require('node:vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = \"vm\";');\nconsole.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);\n// Prints: vmResult: 'vm', localVar: 'initial value'\n\nconst evalResult = eval('localVar = \"eval\";');\nconsole.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);\n// Prints: evalResult: 'eval', localVar: 'eval'\n</code></pre>\n<p>Because <code>vm.runInThisContext()</code> does not have access to the local scope,\n<code>localVar</code> is unchanged. In contrast, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\"><code>eval()</code></a> <em>does</em> have access to the\nlocal scope, so the value <code>localVar</code> is changed. In this way\n<code>vm.runInThisContext()</code> is much like an <a href=\"https://es5.github.io/#x10.4.2\">indirect <code>eval()</code> call</a>, e.g.\n<code>(0,eval)('code')</code>.</p>\n<h2>Example: Running an HTTP server within a VM</h2>\n<p>When using either <a href=\"#scriptruninthiscontextoptions\"><code>script.runInThisContext()</code></a> or\n<a href=\"#vmruninthiscontextcode-options\"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.</p>\n<p>In order to run a simple web server using the <code>node:http</code> module the code passed\nto the context must either call <code>require('node:http')</code> on its own, or have a\nreference to the <code>node:http</code> module passed to it. For instance:</p>\n<pre><code class=\"language-js\">'use strict';\nconst vm = require('node:vm');\n\nconst code = `\n((require) => {\n const http = require('node:http');\n\n http.createServer((request, response) => {\n response.writeHead(200, { 'Content-Type': 'text/plain' });\n response.end('Hello World\\\\n');\n }).listen(8124);\n\n console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n</code></pre>\n<p>The <code>require()</code> 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.</p>" 1521 } 1522 ], 1523 "modules": [ 1524 { 1525 "textRaw": "What does it mean to \"contextify\" an object?", 1526 "name": "what_does_it_mean_to_\"contextify\"_an_object?", 1527 "desc": "<p>All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the <a href=\"https://v8.dev/docs/embed#contexts\">V8 Embedder's Guide</a>:</p>\n<blockquote>\n<p>In V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.</p>\n</blockquote>\n<p>When the method <code>vm.createContext()</code> is called, the <code>contextObject</code> argument\n(or a newly-created object if <code>contextObject</code> is <code>undefined</code>) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\n<code>code</code> run using the <code>node:vm</code> module's methods with an isolated global\nenvironment within which it can operate. The process of creating the V8 Context\nand associating it with the <code>contextObject</code> is what this document refers to as\n\"contextifying\" the object.</p>", 1528 "type": "module", 1529 "displayName": "What does it mean to \"contextify\" an object?" 1530 }, 1531 { 1532 "textRaw": "Timeout interactions with asynchronous tasks and Promises", 1533 "name": "timeout_interactions_with_asynchronous_tasks_and_promises", 1534 "desc": "<p><code>Promise</code>s and <code>async function</code>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 <code>timeout</code> and\n<code>breakOnSigint</code> options.</p>\n<p>For example, the following code executed by <code>vm.runInNewContext()</code> 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:</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nfunction loop() {\n console.log('entering loop');\n while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n 'Promise.resolve().then(() => loop());',\n { loop, console },\n { timeout: 5 },\n);\n// This is printed *before* 'entering loop' (!)\nconsole.log('done executing');\n</code></pre>\n<p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code\nthat creates the <code>Context</code>:</p>\n<pre><code class=\"language-js\">const vm = require('node:vm');\n\nfunction loop() {\n while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n 'Promise.resolve().then(() => loop());',\n { loop, console },\n { timeout: 5, microtaskMode: 'afterEvaluate' },\n);\n</code></pre>\n<p>In this case, the microtask scheduled through <code>promise.then()</code> will be run\nbefore returning from <code>vm.runInNewContext()</code>, and will be interrupted\nby the <code>timeout</code> functionality. This applies only to code running in a\n<code>vm.Context</code>, so e.g. <a href=\"#vmruninthiscontextcode-options\"><code>vm.runInThisContext()</code></a> does not take this option.</p>\n<p>Promise callbacks are entered into the microtask queue of the context in which\nthey were created. For example, if <code>() => loop()</code> is replaced with just <code>loop</code>\nin the above example, then <code>loop</code> 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.</p>\n<p>If asynchronous scheduling functions such as <code>process.nextTick()</code>,\n<code>queueMicrotask()</code>, <code>setTimeout()</code>, <code>setImmediate()</code>, etc. are made available\ninside a <code>vm.Context</code>, 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.</p>", 1535 "type": "module", 1536 "displayName": "Timeout interactions with asynchronous tasks and Promises" 1537 } 1538 ], 1539 "type": "module", 1540 "displayName": "vm" 1541 } 1542 ] 1543}