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/v14.20.1/lib/vm.js\">lib/vm.js</a></p>\n<p>The <code>vm</code> module enables compiling and running code within V8 Virtual\nMachine contexts. <strong>The <code>vm</code> module is not a security mechanism. Do\nnot 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=\"#vm_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('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 "methods": [ 25 { 26 "textRaw": "`script.createCachedData()`", 27 "type": "method", 28 "name": "createCachedData", 29 "meta": { 30 "added": [ 31 "v10.6.0" 32 ], 33 "changes": [] 34 }, 35 "signatures": [ 36 { 37 "return": { 38 "textRaw": "Returns: {Buffer}", 39 "name": "return", 40 "type": "Buffer" 41 }, 42 "params": [] 43 } 44 ], 45 "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<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 cacheWithoutX = script.createCachedData();\n\nscript.runInThisContext();\n\nconst cacheWithX = script.createCachedData();\n</code></pre>" 46 }, 47 { 48 "textRaw": "`script.runInContext(contextifiedObject[, options])`", 49 "type": "method", 50 "name": "runInContext", 51 "meta": { 52 "added": [ 53 "v0.3.1" 54 ], 55 "changes": [ 56 { 57 "version": "v6.3.0", 58 "pr-url": "https://github.com/nodejs/node/pull/6635", 59 "description": "The `breakOnSigint` option is supported now." 60 } 61 ] 62 }, 63 "signatures": [ 64 { 65 "return": { 66 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 67 "name": "return", 68 "type": "any", 69 "desc": "the result of the very last statement executed in the script." 70 }, 71 "params": [ 72 { 73 "textRaw": "`contextifiedObject` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", 74 "name": "contextifiedObject", 75 "type": "Object", 76 "desc": "A [contextified][] object as returned by the `vm.createContext()` method." 77 }, 78 { 79 "textRaw": "`options` {Object}", 80 "name": "options", 81 "type": "Object", 82 "options": [ 83 { 84 "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`.", 85 "name": "displayErrors", 86 "type": "boolean", 87 "default": "`true`", 88 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 89 }, 90 { 91 "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.", 92 "name": "timeout", 93 "type": "integer", 94 "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." 95 }, 96 { 97 "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`.", 98 "name": "breakOnSigint", 99 "type": "boolean", 100 "default": "`false`", 101 "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." 102 } 103 ] 104 } 105 ] 106 } 107 ], 108 "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('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>" 109 }, 110 { 111 "textRaw": "`script.runInNewContext([contextObject[, options]])`", 112 "type": "method", 113 "name": "runInNewContext", 114 "meta": { 115 "added": [ 116 "v0.3.1" 117 ], 118 "changes": [ 119 { 120 "version": "v14.6.0", 121 "pr-url": "https://github.com/nodejs/node/pull/34023", 122 "description": "The `microtaskMode` option is supported now." 123 }, 124 { 125 "version": "v10.0.0", 126 "pr-url": "https://github.com/nodejs/node/pull/19016", 127 "description": "The `contextCodeGeneration` option is supported now." 128 }, 129 { 130 "version": "v6.3.0", 131 "pr-url": "https://github.com/nodejs/node/pull/6635", 132 "description": "The `breakOnSigint` option is supported now." 133 } 134 ] 135 }, 136 "signatures": [ 137 { 138 "return": { 139 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 140 "name": "return", 141 "type": "any", 142 "desc": "the result of the very last statement executed in the script." 143 }, 144 "params": [ 145 { 146 "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", 147 "name": "contextObject", 148 "type": "Object", 149 "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." 150 }, 151 { 152 "textRaw": "`options` {Object}", 153 "name": "options", 154 "type": "Object", 155 "options": [ 156 { 157 "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`.", 158 "name": "displayErrors", 159 "type": "boolean", 160 "default": "`true`", 161 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 162 }, 163 { 164 "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.", 165 "name": "timeout", 166 "type": "integer", 167 "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." 168 }, 169 { 170 "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`.", 171 "name": "breakOnSigint", 172 "type": "boolean", 173 "default": "`false`", 174 "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." 175 }, 176 { 177 "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.", 178 "name": "contextName", 179 "type": "string", 180 "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", 181 "desc": "Human-readable name of the newly created context." 182 }, 183 { 184 "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:** `''`.", 185 "name": "contextOrigin", 186 "type": "string", 187 "default": "`''`", 188 "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." 189 }, 190 { 191 "textRaw": "`contextCodeGeneration` {Object}", 192 "name": "contextCodeGeneration", 193 "type": "Object", 194 "options": [ 195 { 196 "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", 197 "name": "strings", 198 "type": "boolean", 199 "default": "`true`", 200 "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." 201 }, 202 { 203 "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", 204 "name": "wasm", 205 "type": "boolean", 206 "default": "`true`", 207 "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." 208 } 209 ] 210 }, 211 { 212 "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.", 213 "name": "microtaskMode", 214 "type": "string", 215 "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." 216 } 217 ] 218 } 219 ] 220 } 221 ], 222 "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('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>" 223 }, 224 { 225 "textRaw": "`script.runInThisContext([options])`", 226 "type": "method", 227 "name": "runInThisContext", 228 "meta": { 229 "added": [ 230 "v0.3.1" 231 ], 232 "changes": [ 233 { 234 "version": "v6.3.0", 235 "pr-url": "https://github.com/nodejs/node/pull/6635", 236 "description": "The `breakOnSigint` option is supported now." 237 } 238 ] 239 }, 240 "signatures": [ 241 { 242 "return": { 243 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 244 "name": "return", 245 "type": "any", 246 "desc": "the result of the very last statement executed in the script." 247 }, 248 "params": [ 249 { 250 "textRaw": "`options` {Object}", 251 "name": "options", 252 "type": "Object", 253 "options": [ 254 { 255 "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`.", 256 "name": "displayErrors", 257 "type": "boolean", 258 "default": "`true`", 259 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 260 }, 261 { 262 "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.", 263 "name": "timeout", 264 "type": "integer", 265 "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." 266 }, 267 { 268 "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`.", 269 "name": "breakOnSigint", 270 "type": "boolean", 271 "default": "`false`", 272 "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." 273 } 274 ] 275 } 276 ] 277 } 278 ], 279 "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('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>" 280 } 281 ], 282 "signatures": [ 283 { 284 "params": [ 285 { 286 "textRaw": "`code` {string} The JavaScript code to compile.", 287 "name": "code", 288 "type": "string", 289 "desc": "The JavaScript code to compile." 290 }, 291 { 292 "textRaw": "`options` {Object|string}", 293 "name": "options", 294 "type": "Object|string", 295 "options": [ 296 { 297 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 298 "name": "filename", 299 "type": "string", 300 "default": "`'evalmachine.<anonymous>'`", 301 "desc": "Specifies the filename used in stack traces produced by this script." 302 }, 303 { 304 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 305 "name": "lineOffset", 306 "type": "number", 307 "default": "`0`", 308 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 309 }, 310 { 311 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 312 "name": "columnOffset", 313 "type": "number", 314 "default": "`0`", 315 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 316 }, 317 { 318 "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.", 319 "name": "cachedData", 320 "type": "Buffer|TypedArray|DataView", 321 "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." 322 }, 323 { 324 "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`.", 325 "name": "produceCachedData", 326 "type": "boolean", 327 "default": "`false`", 328 "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()`." 329 }, 330 { 331 "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.", 332 "name": "importModuleDynamically", 333 "type": "Function", 334 "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.", 335 "options": [ 336 { 337 "textRaw": "`specifier` {string} specifier passed to `import()`", 338 "name": "specifier", 339 "type": "string", 340 "desc": "specifier passed to `import()`" 341 }, 342 { 343 "textRaw": "`script` {vm.Script}", 344 "name": "script", 345 "type": "vm.Script" 346 }, 347 { 348 "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.", 349 "name": "return", 350 "type": "Module Namespace Object|vm.Module", 351 "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." 352 } 353 ] 354 } 355 ] 356 } 357 ], 358 "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>" 359 } 360 ] 361 }, 362 { 363 "textRaw": "Class: `vm.Module`", 364 "type": "class", 365 "name": "vm.Module", 366 "meta": { 367 "added": [ 368 "v13.0.0", 369 "v12.16.0" 370 ], 371 "changes": [] 372 }, 373 "stability": 1, 374 "stabilityText": "Experimental", 375 "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#esm_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 '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('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>", 376 "properties": [ 377 { 378 "textRaw": "`dependencySpecifiers` {string[]}", 379 "type": "string[]", 380 "name": "dependencySpecifiers", 381 "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>" 382 }, 383 { 384 "textRaw": "`error` {any}", 385 "type": "any", 386 "name": "error", 387 "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>" 388 }, 389 { 390 "textRaw": "`identifier` {string}", 391 "type": "string", 392 "name": "identifier", 393 "desc": "<p>The identifier of the current module, as set in the constructor.</p>" 394 }, 395 { 396 "textRaw": "`namespace` {Object}", 397 "type": "Object", 398 "name": "namespace", 399 "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>" 400 }, 401 { 402 "textRaw": "`status` {string}", 403 "type": "string", 404 "name": "status", 405 "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>" 406 } 407 ], 408 "methods": [ 409 { 410 "textRaw": "`module.evaluate([options])`", 411 "type": "method", 412 "name": "evaluate", 413 "signatures": [ 414 { 415 "return": { 416 "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", 417 "name": "return", 418 "type": "Promise", 419 "desc": "Fulfills with `undefined` upon success." 420 }, 421 "params": [ 422 { 423 "textRaw": "`options` {Object}", 424 "name": "options", 425 "type": "Object", 426 "options": [ 427 { 428 "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.", 429 "name": "timeout", 430 "type": "integer", 431 "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." 432 }, 433 { 434 "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`.", 435 "name": "breakOnSigint", 436 "type": "boolean", 437 "default": "`false`", 438 "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." 439 } 440 ] 441 } 442 ] 443 } 444 ], 445 "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>" 446 }, 447 { 448 "textRaw": "`module.link(linker)`", 449 "type": "method", 450 "name": "link", 451 "signatures": [ 452 { 453 "return": { 454 "textRaw": "Returns: {Promise}", 455 "name": "return", 456 "type": "Promise" 457 }, 458 "params": [ 459 { 460 "textRaw": "`linker` {Function}", 461 "name": "linker", 462 "type": "Function", 463 "options": [ 464 { 465 "textRaw": "`specifier` {string} The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```", 466 "name": "specifier", 467 "type": "string", 468 "desc": "The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```" 469 }, 470 { 471 "textRaw": "`referencingModule` {vm.Module} The `Module` object `link()` is called on.", 472 "name": "referencingModule", 473 "type": "vm.Module", 474 "desc": "The `Module` object `link()` is called on." 475 }, 476 { 477 "textRaw": "Returns: {vm.Module|Promise}", 478 "name": "return", 479 "type": "vm.Module|Promise" 480 } 481 ] 482 } 483 ] 484 } 485 ], 486 "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>" 487 } 488 ] 489 }, 490 { 491 "textRaw": "Class: `vm.SourceTextModule`", 492 "type": "class", 493 "name": "vm.SourceTextModule", 494 "meta": { 495 "added": [ 496 "v9.6.0" 497 ], 498 "changes": [] 499 }, 500 "stability": 1, 501 "stabilityText": "Experimental", 502 "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#vm_class_vm_module\" 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>", 503 "methods": [ 504 { 505 "textRaw": "`sourceTextModule.createCachedData()`", 506 "type": "method", 507 "name": "createCachedData", 508 "meta": { 509 "added": [ 510 "v13.7.0" 511 ], 512 "changes": [] 513 }, 514 "signatures": [ 515 { 516 "return": { 517 "textRaw": "Returns: {Buffer}", 518 "name": "return", 519 "type": "Buffer" 520 }, 521 "params": [] 522 } 523 ], 524 "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<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>" 525 } 526 ], 527 "signatures": [ 528 { 529 "params": [ 530 { 531 "textRaw": "`code` {string} JavaScript Module code to parse", 532 "name": "code", 533 "type": "string", 534 "desc": "JavaScript Module code to parse" 535 }, 536 { 537 "textRaw": "`options`", 538 "name": "options", 539 "options": [ 540 { 541 "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", 542 "name": "identifier", 543 "type": "string", 544 "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", 545 "desc": "String used in stack traces." 546 }, 547 { 548 "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.", 549 "name": "cachedData", 550 "type": "Buffer|TypedArray|DataView", 551 "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." 552 }, 553 { 554 "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", 555 "name": "context", 556 "type": "Object", 557 "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." 558 }, 559 { 560 "textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", 561 "name": "lineOffset", 562 "type": "integer", 563 "default": "`0`", 564 "desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`." 565 }, 566 { 567 "textRaw": "`columnOffset` {integer} Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", 568 "name": "columnOffset", 569 "type": "integer", 570 "default": "`0`", 571 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`." 572 }, 573 { 574 "textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.", 575 "name": "initializeImportMeta", 576 "type": "Function", 577 "desc": "Called during evaluation of this `Module` to initialize the `import.meta`.", 578 "options": [ 579 { 580 "textRaw": "`meta` {import.meta}", 581 "name": "meta", 582 "type": "import.meta" 583 }, 584 { 585 "textRaw": "`module` {vm.SourceTextModule}", 586 "name": "module", 587 "type": "vm.SourceTextModule" 588 } 589 ] 590 }, 591 { 592 "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`][].", 593 "name": "importModuleDynamically", 594 "type": "Function", 595 "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`][].", 596 "options": [ 597 { 598 "textRaw": "`specifier` {string} specifier passed to `import()`", 599 "name": "specifier", 600 "type": "string", 601 "desc": "specifier passed to `import()`" 602 }, 603 { 604 "textRaw": "`module` {vm.Module}", 605 "name": "module", 606 "type": "vm.Module" 607 }, 608 { 609 "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.", 610 "name": "return", 611 "type": "Module Namespace Object|vm.Module", 612 "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." 613 } 614 ] 615 } 616 ] 617 } 618 ], 619 "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 '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('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>" 620 } 621 ] 622 }, 623 { 624 "textRaw": "Class: `vm.SyntheticModule`", 625 "type": "class", 626 "name": "vm.SyntheticModule", 627 "meta": { 628 "added": [ 629 "v13.0.0", 630 "v12.16.0" 631 ], 632 "changes": [] 633 }, 634 "stability": 1, 635 "stabilityText": "Experimental", 636 "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#vm_class_vm_module\" 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('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>", 637 "methods": [ 638 { 639 "textRaw": "`syntheticModule.setExport(name, value)`", 640 "type": "method", 641 "name": "setExport", 642 "meta": { 643 "added": [ 644 "v13.0.0", 645 "v12.16.0" 646 ], 647 "changes": [] 648 }, 649 "signatures": [ 650 { 651 "params": [ 652 { 653 "textRaw": "`name` {string} Name of the export to set.", 654 "name": "name", 655 "type": "string", 656 "desc": "Name of the export to set." 657 }, 658 { 659 "textRaw": "`value` {any} The value to set the export to.", 660 "name": "value", 661 "type": "any", 662 "desc": "The value to set the export to." 663 } 664 ] 665 } 666 ], 667 "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 '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('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>" 668 } 669 ], 670 "signatures": [ 671 { 672 "params": [ 673 { 674 "textRaw": "`exportNames` {string[]} Array of names that will be exported from the module.", 675 "name": "exportNames", 676 "type": "string[]", 677 "desc": "Array of names that will be exported from the module." 678 }, 679 { 680 "textRaw": "`evaluateCallback` {Function} Called when the module is evaluated.", 681 "name": "evaluateCallback", 682 "type": "Function", 683 "desc": "Called when the module is evaluated." 684 }, 685 { 686 "textRaw": "`options`**Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", 687 "name": "options", 688 "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", 689 "options": [ 690 { 691 "textRaw": "`identifier` {string} String used in stack traces.", 692 "name": "identifier", 693 "type": "string", 694 "desc": "String used in stack traces." 695 } 696 ] 697 } 698 ], 699 "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>" 700 } 701 ] 702 } 703 ], 704 "methods": [ 705 { 706 "textRaw": "`vm.compileFunction(code[, params[, options]])`", 707 "type": "method", 708 "name": "compileFunction", 709 "meta": { 710 "added": [ 711 "v10.10.0" 712 ], 713 "changes": [ 714 { 715 "version": "v14.3.0", 716 "pr-url": "https://github.com/nodejs/node/pull/33364", 717 "description": "Removal of `importModuleDynamically` due to compatibility issues." 718 }, 719 { 720 "version": [ 721 "v14.1.0", 722 "v13.14.0" 723 ], 724 "pr-url": "https://github.com/nodejs/node/pull/32985", 725 "description": "The `importModuleDynamically` option is now supported." 726 } 727 ] 728 }, 729 "signatures": [ 730 { 731 "return": { 732 "textRaw": "Returns: {Function}", 733 "name": "return", 734 "type": "Function" 735 }, 736 "params": [ 737 { 738 "textRaw": "`code` {string} The body of the function to compile.", 739 "name": "code", 740 "type": "string", 741 "desc": "The body of the function to compile." 742 }, 743 { 744 "textRaw": "`params` {string[]} An array of strings containing all parameters for the function.", 745 "name": "params", 746 "type": "string[]", 747 "desc": "An array of strings containing all parameters for the function." 748 }, 749 { 750 "textRaw": "`options` {Object}", 751 "name": "options", 752 "type": "Object", 753 "options": [ 754 { 755 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `''`.", 756 "name": "filename", 757 "type": "string", 758 "default": "`''`", 759 "desc": "Specifies the filename used in stack traces produced by this script." 760 }, 761 { 762 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 763 "name": "lineOffset", 764 "type": "number", 765 "default": "`0`", 766 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 767 }, 768 { 769 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 770 "name": "columnOffset", 771 "type": "number", 772 "default": "`0`", 773 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 774 }, 775 { 776 "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", 777 "name": "cachedData", 778 "type": "Buffer|TypedArray|DataView", 779 "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." 780 }, 781 { 782 "textRaw": "`produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`.", 783 "name": "produceCachedData", 784 "type": "boolean", 785 "default": "`false`", 786 "desc": "Specifies whether to produce new cache data." 787 }, 788 { 789 "textRaw": "`parsingContext` {Object} The [contextified][] object in which the said function should be compiled in.", 790 "name": "parsingContext", 791 "type": "Object", 792 "desc": "The [contextified][] object in which the said function should be compiled in." 793 }, 794 { 795 "textRaw": "`contextExtensions` {Object[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`.", 796 "name": "contextExtensions", 797 "type": "Object[]", 798 "default": "`[]`", 799 "desc": "An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling." 800 } 801 ] 802 } 803 ] 804 } 805 ], 806 "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>" 807 }, 808 { 809 "textRaw": "`vm.createContext([contextObject[, options]])`", 810 "type": "method", 811 "name": "createContext", 812 "meta": { 813 "added": [ 814 "v0.3.1" 815 ], 816 "changes": [ 817 { 818 "version": "v14.6.0", 819 "pr-url": "https://github.com/nodejs/node/pull/34023", 820 "description": "The `microtaskMode` option is supported now." 821 }, 822 { 823 "version": "v10.0.0", 824 "pr-url": "https://github.com/nodejs/node/pull/19398", 825 "description": "The first argument can no longer be a function." 826 }, 827 { 828 "version": "v10.0.0", 829 "pr-url": "https://github.com/nodejs/node/pull/19016", 830 "description": "The `codeGeneration` option is supported now." 831 } 832 ] 833 }, 834 "signatures": [ 835 { 836 "return": { 837 "textRaw": "Returns: {Object} contextified object.", 838 "name": "return", 839 "type": "Object", 840 "desc": "contextified object." 841 }, 842 "params": [ 843 { 844 "textRaw": "`contextObject` {Object}", 845 "name": "contextObject", 846 "type": "Object" 847 }, 848 { 849 "textRaw": "`options` {Object}", 850 "name": "options", 851 "type": "Object", 852 "options": [ 853 { 854 "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.", 855 "name": "name", 856 "type": "string", 857 "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", 858 "desc": "Human-readable name of the newly created context." 859 }, 860 { 861 "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:** `''`.", 862 "name": "origin", 863 "type": "string", 864 "default": "`''`", 865 "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." 866 }, 867 { 868 "textRaw": "`codeGeneration` {Object}", 869 "name": "codeGeneration", 870 "type": "Object", 871 "options": [ 872 { 873 "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", 874 "name": "strings", 875 "type": "boolean", 876 "default": "`true`", 877 "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." 878 }, 879 { 880 "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", 881 "name": "wasm", 882 "type": "boolean", 883 "default": "`true`", 884 "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." 885 } 886 ] 887 }, 888 { 889 "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.", 890 "name": "microtaskMode", 891 "type": "string", 892 "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." 893 } 894 ] 895 } 896 ] 897 } 898 ], 899 "desc": "<p>If given a <code>contextObject</code>, the <code>vm.createContext()</code> method will <a href=\"#vm_what_does_it_mean_to_contextify_an_object\">prepare\nthat object</a> so that it can be used in calls to\n<a href=\"#vm_vm_runincontext_code_contextifiedobject_options\"><code>vm.runInContext()</code></a> or <a href=\"#vm_script_runincontext_contextifiedobject_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('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=\"#vm_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>" 900 }, 901 { 902 "textRaw": "`vm.isContext(object)`", 903 "type": "method", 904 "name": "isContext", 905 "meta": { 906 "added": [ 907 "v0.11.7" 908 ], 909 "changes": [] 910 }, 911 "signatures": [ 912 { 913 "return": { 914 "textRaw": "Returns: {boolean}", 915 "name": "return", 916 "type": "boolean" 917 }, 918 "params": [ 919 { 920 "textRaw": "`object` {Object}", 921 "name": "object", 922 "type": "Object" 923 } 924 ] 925 } 926 ], 927 "desc": "<p>Returns <code>true</code> if the given <code>object</code> object has been <a href=\"#vm_what_does_it_mean_to_contextify_an_object\">contextified</a> using\n<a href=\"#vm_vm_createcontext_contextobject_options\"><code>vm.createContext()</code></a>.</p>" 928 }, 929 { 930 "textRaw": "`vm.measureMemory([options])`", 931 "type": "method", 932 "name": "measureMemory", 933 "meta": { 934 "added": [ 935 "v13.10.0" 936 ], 937 "changes": [] 938 }, 939 "stability": 1, 940 "stabilityText": "Experimental", 941 "signatures": [ 942 { 943 "params": [] 944 } 945 ], 946 "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 measure 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.</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('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>" 947 }, 948 { 949 "textRaw": "`vm.runInContext(code, contextifiedObject[, options])`", 950 "type": "method", 951 "name": "runInContext", 952 "meta": { 953 "added": [ 954 "v0.3.1" 955 ], 956 "changes": [ 957 { 958 "version": "v6.3.0", 959 "pr-url": "https://github.com/nodejs/node/pull/6635", 960 "description": "The `breakOnSigint` option is supported now." 961 } 962 ] 963 }, 964 "signatures": [ 965 { 966 "return": { 967 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 968 "name": "return", 969 "type": "any", 970 "desc": "the result of the very last statement executed in the script." 971 }, 972 "params": [ 973 { 974 "textRaw": "`code` {string} The JavaScript code to compile and run.", 975 "name": "code", 976 "type": "string", 977 "desc": "The JavaScript code to compile and run." 978 }, 979 { 980 "textRaw": "`contextifiedObject` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.", 981 "name": "contextifiedObject", 982 "type": "Object", 983 "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." 984 }, 985 { 986 "textRaw": "`options` {Object|string}", 987 "name": "options", 988 "type": "Object|string", 989 "options": [ 990 { 991 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 992 "name": "filename", 993 "type": "string", 994 "default": "`'evalmachine.<anonymous>'`", 995 "desc": "Specifies the filename used in stack traces produced by this script." 996 }, 997 { 998 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 999 "name": "lineOffset", 1000 "type": "number", 1001 "default": "`0`", 1002 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 1003 }, 1004 { 1005 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1006 "name": "columnOffset", 1007 "type": "number", 1008 "default": "`0`", 1009 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 1010 }, 1011 { 1012 "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`.", 1013 "name": "displayErrors", 1014 "type": "boolean", 1015 "default": "`true`", 1016 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 1017 }, 1018 { 1019 "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.", 1020 "name": "timeout", 1021 "type": "integer", 1022 "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." 1023 }, 1024 { 1025 "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`.", 1026 "name": "breakOnSigint", 1027 "type": "boolean", 1028 "default": "`false`", 1029 "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." 1030 }, 1031 { 1032 "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.", 1033 "name": "cachedData", 1034 "type": "Buffer|TypedArray|DataView", 1035 "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." 1036 }, 1037 { 1038 "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`.", 1039 "name": "produceCachedData", 1040 "type": "boolean", 1041 "default": "`false`", 1042 "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()`." 1043 }, 1044 { 1045 "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.", 1046 "name": "importModuleDynamically", 1047 "type": "Function", 1048 "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.", 1049 "options": [ 1050 { 1051 "textRaw": "`specifier` {string} specifier passed to `import()`", 1052 "name": "specifier", 1053 "type": "string", 1054 "desc": "specifier passed to `import()`" 1055 }, 1056 { 1057 "textRaw": "`script` {vm.Script}", 1058 "name": "script", 1059 "type": "vm.Script" 1060 }, 1061 { 1062 "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.", 1063 "name": "return", 1064 "type": "Module Namespace Object|vm.Module", 1065 "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." 1066 } 1067 ] 1068 } 1069 ] 1070 } 1071 ] 1072 } 1073 ], 1074 "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=\"#vm_what_does_it_mean_to_contextify_an_object\">contextified</a> using the <a href=\"#vm_vm_createcontext_contextobject_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=\"#vm_what_does_it_mean_to_contextify_an_object\">contextified</a> object:</p>\n<pre><code class=\"language-js\">const vm = require('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>" 1075 }, 1076 { 1077 "textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`", 1078 "type": "method", 1079 "name": "runInNewContext", 1080 "meta": { 1081 "added": [ 1082 "v0.3.1" 1083 ], 1084 "changes": [ 1085 { 1086 "version": "v14.6.0", 1087 "pr-url": "https://github.com/nodejs/node/pull/34023", 1088 "description": "The `microtaskMode` option is supported now." 1089 }, 1090 { 1091 "version": "v10.0.0", 1092 "pr-url": "https://github.com/nodejs/node/pull/19016", 1093 "description": "The `contextCodeGeneration` option is supported now." 1094 }, 1095 { 1096 "version": "v6.3.0", 1097 "pr-url": "https://github.com/nodejs/node/pull/6635", 1098 "description": "The `breakOnSigint` option is supported now." 1099 } 1100 ] 1101 }, 1102 "signatures": [ 1103 { 1104 "return": { 1105 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 1106 "name": "return", 1107 "type": "any", 1108 "desc": "the result of the very last statement executed in the script." 1109 }, 1110 "params": [ 1111 { 1112 "textRaw": "`code` {string} The JavaScript code to compile and run.", 1113 "name": "code", 1114 "type": "string", 1115 "desc": "The JavaScript code to compile and run." 1116 }, 1117 { 1118 "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", 1119 "name": "contextObject", 1120 "type": "Object", 1121 "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." 1122 }, 1123 { 1124 "textRaw": "`options` {Object|string}", 1125 "name": "options", 1126 "type": "Object|string", 1127 "options": [ 1128 { 1129 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 1130 "name": "filename", 1131 "type": "string", 1132 "default": "`'evalmachine.<anonymous>'`", 1133 "desc": "Specifies the filename used in stack traces produced by this script." 1134 }, 1135 { 1136 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1137 "name": "lineOffset", 1138 "type": "number", 1139 "default": "`0`", 1140 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 1141 }, 1142 { 1143 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1144 "name": "columnOffset", 1145 "type": "number", 1146 "default": "`0`", 1147 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 1148 }, 1149 { 1150 "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`.", 1151 "name": "displayErrors", 1152 "type": "boolean", 1153 "default": "`true`", 1154 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 1155 }, 1156 { 1157 "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.", 1158 "name": "timeout", 1159 "type": "integer", 1160 "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." 1161 }, 1162 { 1163 "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`.", 1164 "name": "breakOnSigint", 1165 "type": "boolean", 1166 "default": "`false`", 1167 "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." 1168 }, 1169 { 1170 "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.", 1171 "name": "contextName", 1172 "type": "string", 1173 "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", 1174 "desc": "Human-readable name of the newly created context." 1175 }, 1176 { 1177 "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:** `''`.", 1178 "name": "contextOrigin", 1179 "type": "string", 1180 "default": "`''`", 1181 "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." 1182 }, 1183 { 1184 "textRaw": "`contextCodeGeneration` {Object}", 1185 "name": "contextCodeGeneration", 1186 "type": "Object", 1187 "options": [ 1188 { 1189 "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", 1190 "name": "strings", 1191 "type": "boolean", 1192 "default": "`true`", 1193 "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." 1194 }, 1195 { 1196 "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", 1197 "name": "wasm", 1198 "type": "boolean", 1199 "default": "`true`", 1200 "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." 1201 } 1202 ] 1203 }, 1204 { 1205 "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.", 1206 "name": "cachedData", 1207 "type": "Buffer|TypedArray|DataView", 1208 "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." 1209 }, 1210 { 1211 "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`.", 1212 "name": "produceCachedData", 1213 "type": "boolean", 1214 "default": "`false`", 1215 "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()`." 1216 }, 1217 { 1218 "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.", 1219 "name": "importModuleDynamically", 1220 "type": "Function", 1221 "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.", 1222 "options": [ 1223 { 1224 "textRaw": "`specifier` {string} specifier passed to `import()`", 1225 "name": "specifier", 1226 "type": "string", 1227 "desc": "specifier passed to `import()`" 1228 }, 1229 { 1230 "textRaw": "`script` {vm.Script}", 1231 "name": "script", 1232 "type": "vm.Script" 1233 }, 1234 { 1235 "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.", 1236 "name": "return", 1237 "type": "Module Namespace Object|vm.Module", 1238 "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." 1239 } 1240 ] 1241 }, 1242 { 1243 "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.", 1244 "name": "microtaskMode", 1245 "type": "string", 1246 "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." 1247 } 1248 ] 1249 } 1250 ] 1251 } 1252 ], 1253 "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('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>" 1254 }, 1255 { 1256 "textRaw": "`vm.runInThisContext(code[, options])`", 1257 "type": "method", 1258 "name": "runInThisContext", 1259 "meta": { 1260 "added": [ 1261 "v0.3.1" 1262 ], 1263 "changes": [ 1264 { 1265 "version": "v6.3.0", 1266 "pr-url": "https://github.com/nodejs/node/pull/6635", 1267 "description": "The `breakOnSigint` option is supported now." 1268 } 1269 ] 1270 }, 1271 "signatures": [ 1272 { 1273 "return": { 1274 "textRaw": "Returns: {any} the result of the very last statement executed in the script.", 1275 "name": "return", 1276 "type": "any", 1277 "desc": "the result of the very last statement executed in the script." 1278 }, 1279 "params": [ 1280 { 1281 "textRaw": "`code` {string} The JavaScript code to compile and run.", 1282 "name": "code", 1283 "type": "string", 1284 "desc": "The JavaScript code to compile and run." 1285 }, 1286 { 1287 "textRaw": "`options` {Object|string}", 1288 "name": "options", 1289 "type": "Object|string", 1290 "options": [ 1291 { 1292 "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.<anonymous>'`.", 1293 "name": "filename", 1294 "type": "string", 1295 "default": "`'evalmachine.<anonymous>'`", 1296 "desc": "Specifies the filename used in stack traces produced by this script." 1297 }, 1298 { 1299 "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1300 "name": "lineOffset", 1301 "type": "number", 1302 "default": "`0`", 1303 "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." 1304 }, 1305 { 1306 "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", 1307 "name": "columnOffset", 1308 "type": "number", 1309 "default": "`0`", 1310 "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." 1311 }, 1312 { 1313 "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`.", 1314 "name": "displayErrors", 1315 "type": "boolean", 1316 "default": "`true`", 1317 "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." 1318 }, 1319 { 1320 "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.", 1321 "name": "timeout", 1322 "type": "integer", 1323 "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." 1324 }, 1325 { 1326 "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`.", 1327 "name": "breakOnSigint", 1328 "type": "boolean", 1329 "default": "`false`", 1330 "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." 1331 }, 1332 { 1333 "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.", 1334 "name": "cachedData", 1335 "type": "Buffer|TypedArray|DataView", 1336 "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." 1337 }, 1338 { 1339 "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`.", 1340 "name": "produceCachedData", 1341 "type": "boolean", 1342 "default": "`false`", 1343 "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()`." 1344 }, 1345 { 1346 "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.", 1347 "name": "importModuleDynamically", 1348 "type": "Function", 1349 "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.", 1350 "options": [ 1351 { 1352 "textRaw": "`specifier` {string} specifier passed to `import()`", 1353 "name": "specifier", 1354 "type": "string", 1355 "desc": "specifier passed to `import()`" 1356 }, 1357 { 1358 "textRaw": "`script` {vm.Script}", 1359 "name": "script", 1360 "type": "vm.Script" 1361 }, 1362 { 1363 "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.", 1364 "name": "return", 1365 "type": "Module Namespace Object|vm.Module", 1366 "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." 1367 } 1368 ] 1369 } 1370 ] 1371 } 1372 ] 1373 } 1374 ], 1375 "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('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=\"#vm_script_runinthiscontext_options\"><code>script.runInThisContext()</code></a> or\n<a href=\"#vm_vm_runinthiscontext_code_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>http</code> module the code passed to\nthe context must either call <code>require('http')</code> on its own, or have a reference\nto the <code>http</code> module passed to it. For instance:</p>\n<pre><code class=\"language-js\">'use strict';\nconst vm = require('vm');\n\nconst code = `\n((require) => {\n const http = require('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>" 1376 } 1377 ], 1378 "modules": [ 1379 { 1380 "textRaw": "What does it mean to \"contextify\" an object?", 1381 "name": "what_does_it_mean_to_\"contextify\"_an_object?", 1382 "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>vm</code> module's methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the <code>contextObject</code> is what this document refers to as\n\"contextifying\" the object.</p>", 1383 "type": "module", 1384 "displayName": "What does it mean to \"contextify\" an object?" 1385 }, 1386 { 1387 "textRaw": "Timeout interactions with asynchronous tasks and Promises", 1388 "name": "timeout_interactions_with_asynchronous_tasks_and_promises", 1389 "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('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('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=\"#vm_vm_runinthiscontext_code_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>", 1390 "type": "module", 1391 "displayName": "Timeout interactions with asynchronous tasks and Promises" 1392 } 1393 ], 1394 "type": "module", 1395 "displayName": "vm" 1396 } 1397 ] 1398}