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