Skip to content

Commit 9a61a7a

Browse files
vsemozhetbytaddaleax
authored andcommittedJan 14, 2019
doc: fix section order in vm.md
This PR just places the `vm.SourceTextModule` class section after the `vm.Script` class section, restoring the alphabetical order. PR-URL: #25374 Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent f6c14bd commit 9a61a7a

File tree

1 file changed

+354
-354
lines changed

1 file changed

+354
-354
lines changed
 

‎doc/api/vm.md

+354-354
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,264 @@ console.log(sandbox.y); // 17
4343
console.log(x); // 1; y is not defined.
4444
```
4545

46+
## Class: vm.Script
47+
<!-- YAML
48+
added: v0.3.1
49+
-->
50+
51+
Instances of the `vm.Script` class contain precompiled scripts that can be
52+
executed in specific sandboxes (or "contexts").
53+
54+
### Constructor: new vm.Script(code[, options])
55+
<!-- YAML
56+
added: v0.3.1
57+
changes:
58+
- version: v5.7.0
59+
pr-url: https://github.com/nodejs/node/pull/4777
60+
description: The `cachedData` and `produceCachedData` options are
61+
supported now.
62+
- version: v10.6.0
63+
pr-url: https://github.com/nodejs/node/pull/20300
64+
description: The `produceCachedData` is deprecated in favour of
65+
`script.createCachedData()`
66+
-->
67+
68+
* `code` {string} The JavaScript code to compile.
69+
* `options` {Object|string}
70+
* `filename` {string} Specifies the filename used in stack traces produced
71+
by this script. **Default:** `'evalmachine.<anonymous>'`.
72+
* `lineOffset` {number} Specifies the line number offset that is displayed
73+
in stack traces produced by this script. **Default:** `0`.
74+
* `columnOffset` {number} Specifies the column number offset that is displayed
75+
in stack traces produced by this script. **Default:** `0`.
76+
* `cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or
77+
`TypedArray`, or `DataView` with V8's code cache data for the supplied
78+
source. When supplied, the `cachedDataRejected` value will be set to
79+
either `true` or `false` depending on acceptance of the data by V8.
80+
* `produceCachedData` {boolean} When `true` and no `cachedData` is present, V8
81+
will attempt to produce code cache data for `code`. Upon success, a
82+
`Buffer` with V8's code cache data will be produced and stored in the
83+
`cachedData` property of the returned `vm.Script` instance.
84+
The `cachedDataProduced` value will be set to either `true` or `false`
85+
depending on whether code cache data is produced successfully.
86+
This option is **deprecated** in favor of `script.createCachedData()`.
87+
**Default:** `false`.
88+
* `importModuleDynamically` {Function} Called during evaluation of this module
89+
when `import()` is called. If this option is not specified, calls to
90+
`import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].
91+
This option is part of the experimental API for the `--experimental-modules`
92+
flag, and should not be considered stable.
93+
* `specifier` {string} specifier passed to `import()`
94+
* `module` {vm.SourceTextModule}
95+
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
96+
`vm.SourceTextModule` is recommended in order to take advantage of error
97+
tracking, and to avoid issues with namespaces that contain `then`
98+
function exports.
99+
100+
If `options` is a string, then it specifies the filename.
101+
102+
Creating a new `vm.Script` object compiles `code` but does not run it. The
103+
compiled `vm.Script` can be run later multiple times. The `code` is not bound to
104+
any global object; rather, it is bound before each run, just for that run.
105+
106+
### script.createCachedData()
107+
<!-- YAML
108+
added: v10.6.0
109+
-->
110+
111+
* Returns: {Buffer}
112+
113+
Creates a code cache that can be used with the Script constructor's
114+
`cachedData` option. Returns a Buffer. This method may be called at any
115+
time and any number of times.
116+
117+
```js
118+
const script = new vm.Script(`
119+
function add(a, b) {
120+
return a + b;
121+
}
122+
123+
const x = add(1, 2);
124+
`);
125+
126+
const cacheWithoutX = script.createCachedData();
127+
128+
script.runInThisContext();
129+
130+
const cacheWithX = script.createCachedData();
131+
```
132+
133+
### script.runInContext(contextifiedSandbox[, options])
134+
<!-- YAML
135+
added: v0.3.1
136+
changes:
137+
- version: v6.3.0
138+
pr-url: https://github.com/nodejs/node/pull/6635
139+
description: The `breakOnSigint` option is supported now.
140+
-->
141+
142+
* `contextifiedSandbox` {Object} A [contextified][] object as returned by the
143+
`vm.createContext()` method.
144+
* `options` {Object}
145+
* `displayErrors` {boolean} When `true`, if an [`Error`][] occurs
146+
while compiling the `code`, the line of code causing the error is attached
147+
to the stack trace. **Default:** `true`.
148+
* `timeout` {integer} Specifies the number of milliseconds to execute `code`
149+
before terminating execution. If execution is terminated, an [`Error`][]
150+
will be thrown. This value must be a strictly positive integer.
151+
* `breakOnSigint` {boolean} If `true`, the execution will be terminated when
152+
`SIGINT` (Ctrl+C) is received. Existing handlers for the
153+
event that have been attached via `process.on('SIGINT')` will be disabled
154+
during script execution, but will continue to work after that. If execution
155+
is terminated, an [`Error`][] will be thrown. **Default:** `false`.
156+
* Returns: {any} the result of the very last statement executed in the script.
157+
158+
Runs the compiled code contained by the `vm.Script` object within the given
159+
`contextifiedSandbox` and returns the result. Running code does not have access
160+
to local scope.
161+
162+
The following example compiles code that increments a global variable, sets
163+
the value of another global variable, then execute the code multiple times.
164+
The globals are contained in the `sandbox` object.
165+
166+
```js
167+
const util = require('util');
168+
const vm = require('vm');
169+
170+
const sandbox = {
171+
animal: 'cat',
172+
count: 2
173+
};
174+
175+
const script = new vm.Script('count += 1; name = "kitty";');
176+
177+
const context = vm.createContext(sandbox);
178+
for (let i = 0; i < 10; ++i) {
179+
script.runInContext(context);
180+
}
181+
182+
console.log(util.inspect(sandbox));
183+
184+
// { animal: 'cat', count: 12, name: 'kitty' }
185+
```
186+
187+
Using the `timeout` or `breakOnSigint` options will result in new event loops
188+
and corresponding threads being started, which have a non-zero performance
189+
overhead.
190+
191+
### script.runInNewContext([sandbox[, options]])
192+
<!-- YAML
193+
added: v0.3.1
194+
changes:
195+
- version: v10.0.0
196+
pr-url: https://github.com/nodejs/node/pull/19016
197+
description: The `contextCodeGeneration` option is supported now.
198+
- version: v6.3.0
199+
pr-url: https://github.com/nodejs/node/pull/6635
200+
description: The `breakOnSigint` option is supported now.
201+
-->
202+
203+
* `sandbox` {Object} An object that will be [contextified][]. If `undefined`, a
204+
new object will be created.
205+
* `options` {Object}
206+
* `displayErrors` {boolean} When `true`, if an [`Error`][] occurs
207+
while compiling the `code`, the line of code causing the error is attached
208+
to the stack trace. **Default:** `true`.
209+
* `timeout` {integer} Specifies the number of milliseconds to execute `code`
210+
before terminating execution. If execution is terminated, an [`Error`][]
211+
will be thrown. This value must be a strictly positive integer.
212+
* `breakOnSigint` {boolean} If `true`, the execution will be terminated when
213+
`SIGINT` (Ctrl+C) is received. Existing handlers for the
214+
event that have been attached via `process.on('SIGINT')` will be disabled
215+
during script execution, but will continue to work after that. If execution
216+
is terminated, an [`Error`][] will be thrown. **Default:** `false`.
217+
* `contextName` {string} Human-readable name of the newly created context.
218+
**Default:** `'VM Context i'`, where `i` is an ascending numerical index of
219+
the created context.
220+
* `contextOrigin` {string} [Origin][origin] corresponding to the newly
221+
created context for display purposes. The origin should be formatted like a
222+
URL, but with only the scheme, host, and port (if necessary), like the
223+
value of the [`url.origin`][] property of a [`URL`][] object. Most notably,
224+
this string should omit the trailing slash, as that denotes a path.
225+
**Default:** `''`.
226+
* `contextCodeGeneration` {Object}
227+
* `strings` {boolean} If set to false any calls to `eval` or function
228+
constructors (`Function`, `GeneratorFunction`, etc) will throw an
229+
`EvalError`. **Default:** `true`.
230+
* `wasm` {boolean} If set to false any attempt to compile a WebAssembly
231+
module will throw a `WebAssembly.CompileError`. **Default:** `true`.
232+
* Returns: {any} the result of the very last statement executed in the script.
233+
234+
First contextifies the given `sandbox`, runs the compiled code contained by
235+
the `vm.Script` object within the created sandbox, and returns the result.
236+
Running code does not have access to local scope.
237+
238+
The following example compiles code that sets a global variable, then executes
239+
the code multiple times in different contexts. The globals are set on and
240+
contained within each individual `sandbox`.
241+
242+
```js
243+
const util = require('util');
244+
const vm = require('vm');
245+
246+
const script = new vm.Script('globalVar = "set"');
247+
248+
const sandboxes = [{}, {}, {}];
249+
sandboxes.forEach((sandbox) => {
250+
script.runInNewContext(sandbox);
251+
});
252+
253+
console.log(util.inspect(sandboxes));
254+
255+
// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
256+
```
257+
258+
### script.runInThisContext([options])
259+
<!-- YAML
260+
added: v0.3.1
261+
changes:
262+
- version: v6.3.0
263+
pr-url: https://github.com/nodejs/node/pull/6635
264+
description: The `breakOnSigint` option is supported now.
265+
-->
266+
267+
* `options` {Object}
268+
* `displayErrors` {boolean} When `true`, if an [`Error`][] occurs
269+
while compiling the `code`, the line of code causing the error is attached
270+
to the stack trace. **Default:** `true`.
271+
* `timeout` {integer} Specifies the number of milliseconds to execute `code`
272+
before terminating execution. If execution is terminated, an [`Error`][]
273+
will be thrown. This value must be a strictly positive integer.
274+
* `breakOnSigint` {boolean} If `true`, the execution will be terminated when
275+
`SIGINT` (Ctrl+C) is received. Existing handlers for the
276+
event that have been attached via `process.on('SIGINT')` will be disabled
277+
during script execution, but will continue to work after that. If execution
278+
is terminated, an [`Error`][] will be thrown. **Default:** `false`.
279+
* Returns: {any} the result of the very last statement executed in the script.
280+
281+
Runs the compiled code contained by the `vm.Script` within the context of the
282+
current `global` object. Running code does not have access to local scope, but
283+
*does* have access to the current `global` object.
284+
285+
The following example compiles code that increments a `global` variable then
286+
executes that code multiple times:
287+
288+
```js
289+
const vm = require('vm');
290+
291+
global.globalVar = 0;
292+
293+
const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
294+
295+
for (let i = 0; i < 1000; ++i) {
296+
script.runInThisContext();
297+
}
298+
299+
console.log(globalVar);
300+
301+
// 1000
302+
```
303+
46304
## Class: vm.SourceTextModule
47305
<!-- YAML
48306
added: v9.6.0
@@ -268,398 +526,140 @@ evaluated, in which case it will do one of the following two things:
268526
evaluation ended in an error (`module.status` is `'errored'`)
269527

270528
This method cannot be called while the module is being evaluated
271-
(`module.status` is `'evaluating'`) to prevent infinite recursion.
272-
273-
Corresponds to the [Evaluate() concrete method][] field of [Source Text Module
274-
Record][]s in the ECMAScript specification.
275-
276-
### module.instantiate()
277-
278-
Instantiate the module. This must be called after linking has completed
279-
(`linkingStatus` is `'linked'`); otherwise it will throw an error. It may also
280-
throw an exception if one of the dependencies does not provide an export the
281-
parent module requires.
282-
283-
However, if this function succeeded, further calls to this function after the
284-
initial instantiation will be no-ops, to be consistent with the ECMAScript
285-
specification.
286-
287-
Unlike other methods operating on `Module`, this function completes
288-
synchronously and returns nothing.
289-
290-
Corresponds to the [Instantiate() concrete method][] field of [Source Text
291-
Module Record][]s in the ECMAScript specification.
292-
293-
### module.link(linker)
294-
295-
* `linker` {Function}
296-
* `specifier` {string} The specifier of the requested module:
297-
<!-- eslint-skip -->
298-
```js
299-
import foo from 'foo';
300-
// ^^^^^ the module specifier
301-
```
302-
* `referencingModule` {vm.SourceTextModule} The `Module` object `link()` is
303-
called on.
304-
* Returns: {vm.SourceTextModule|Promise}
305-
* Returns: {Promise}
306-
307-
Link module dependencies. This method must be called before instantiation, and
308-
can only be called once per module.
309-
310-
The function is expected to return a `Module` object or a `Promise` that
311-
eventually resolves to a `Module` object. The returned `Module` must satisfy the
312-
following two invariants:
313-
314-
- It must belong to the same context as the parent `Module`.
315-
- Its `linkingStatus` must not be `'errored'`.
316-
317-
If the returned `Module`'s `linkingStatus` is `'unlinked'`, this method will be
318-
recursively called on the returned `Module` with the same provided `linker`
319-
function.
320-
321-
`link()` returns a `Promise` that will either get resolved when all linking
322-
instances resolve to a valid `Module`, or rejected if the linker function either
323-
throws an exception or returns an invalid `Module`.
324-
325-
The linker function roughly corresponds to the implementation-defined
326-
[HostResolveImportedModule][] abstract operation in the ECMAScript
327-
specification, with a few key differences:
328-
329-
- The linker function is allowed to be asynchronous while
330-
[HostResolveImportedModule][] is synchronous.
331-
- The linker function is executed during linking, a Node.js-specific stage
332-
before instantiation, while [HostResolveImportedModule][] is called during
333-
instantiation.
334-
335-
The actual [HostResolveImportedModule][] implementation used during module
336-
instantiation is one that returns the modules linked during linking. Since at
337-
that point all modules would have been fully linked already, the
338-
[HostResolveImportedModule][] implementation is fully synchronous per
339-
specification.
340-
341-
### module.linkingStatus
342-
343-
* {string}
344-
345-
The current linking status of `module`. It will be one of the following values:
346-
347-
- `'unlinked'`: `module.link()` has not yet been called.
348-
- `'linking'`: `module.link()` has been called, but not all Promises returned by
349-
the linker function have been resolved yet.
350-
- `'linked'`: `module.link()` has been called, and all its dependencies have
351-
been successfully linked.
352-
- `'errored'`: `module.link()` has been called, but at least one of its
353-
dependencies failed to link, either because the callback returned a `Promise`
354-
that is rejected, or because the `Module` the callback returned is invalid.
355-
356-
### module.namespace
357-
358-
* {Object}
359-
360-
The namespace object of the module. This is only available after instantiation
361-
(`module.instantiate()`) has completed.
362-
363-
Corresponds to the [GetModuleNamespace][] abstract operation in the ECMAScript
364-
specification.
365-
366-
### module.status
367-
368-
* {string}
369-
370-
The current status of the module. Will be one of:
371-
372-
- `'uninstantiated'`: The module is not instantiated. It may because of any of
373-
the following reasons:
374-
375-
- The module was just created.
376-
- `module.instantiate()` has been called on this module, but it failed for
377-
some reason.
378-
379-
This status does not convey any information regarding if `module.link()` has
380-
been called. See `module.linkingStatus` for that.
381-
382-
- `'instantiating'`: The module is currently being instantiated through a
383-
`module.instantiate()` call on itself or a parent module.
384-
385-
- `'instantiated'`: The module has been instantiated successfully, but
386-
`module.evaluate()` has not yet been called.
387-
388-
- `'evaluating'`: The module is being evaluated through a `module.evaluate()` on
389-
itself or a parent module.
390-
391-
- `'evaluated'`: The module has been successfully evaluated.
392-
393-
- `'errored'`: The module has been evaluated, but an exception was thrown.
394-
395-
Other than `'errored'`, this status string corresponds to the specification's
396-
[Source Text Module Record][]'s `[[Status]]` field. `'errored'` corresponds to
397-
`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a
398-
value that is not `undefined`.
399-
400-
### module.url
401-
402-
* {string}
403-
404-
The URL of the current module, as set in the constructor.
405-
406-
## Class: vm.Script
407-
<!-- YAML
408-
added: v0.3.1
409-
-->
410-
411-
Instances of the `vm.Script` class contain precompiled scripts that can be
412-
executed in specific sandboxes (or "contexts").
413-
414-
### Constructor: new vm.Script(code[, options])
415-
<!-- YAML
416-
added: v0.3.1
417-
changes:
418-
- version: v5.7.0
419-
pr-url: https://github.com/nodejs/node/pull/4777
420-
description: The `cachedData` and `produceCachedData` options are
421-
supported now.
422-
- version: v10.6.0
423-
pr-url: https://github.com/nodejs/node/pull/20300
424-
description: The `produceCachedData` is deprecated in favour of
425-
`script.createCachedData()`
426-
-->
427-
428-
* `code` {string} The JavaScript code to compile.
429-
* `options` {Object|string}
430-
* `filename` {string} Specifies the filename used in stack traces produced
431-
by this script. **Default:** `'evalmachine.<anonymous>'`.
432-
* `lineOffset` {number} Specifies the line number offset that is displayed
433-
in stack traces produced by this script. **Default:** `0`.
434-
* `columnOffset` {number} Specifies the column number offset that is displayed
435-
in stack traces produced by this script. **Default:** `0`.
436-
* `cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or
437-
`TypedArray`, or `DataView` with V8's code cache data for the supplied
438-
source. When supplied, the `cachedDataRejected` value will be set to
439-
either `true` or `false` depending on acceptance of the data by V8.
440-
* `produceCachedData` {boolean} When `true` and no `cachedData` is present, V8
441-
will attempt to produce code cache data for `code`. Upon success, a
442-
`Buffer` with V8's code cache data will be produced and stored in the
443-
`cachedData` property of the returned `vm.Script` instance.
444-
The `cachedDataProduced` value will be set to either `true` or `false`
445-
depending on whether code cache data is produced successfully.
446-
This option is **deprecated** in favor of `script.createCachedData()`.
447-
**Default:** `false`.
448-
* `importModuleDynamically` {Function} Called during evaluation of this module
449-
when `import()` is called. If this option is not specified, calls to
450-
`import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].
451-
This option is part of the experimental API for the `--experimental-modules`
452-
flag, and should not be considered stable.
453-
* `specifier` {string} specifier passed to `import()`
454-
* `module` {vm.SourceTextModule}
455-
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
456-
`vm.SourceTextModule` is recommended in order to take advantage of error
457-
tracking, and to avoid issues with namespaces that contain `then`
458-
function exports.
459-
460-
If `options` is a string, then it specifies the filename.
461-
462-
Creating a new `vm.Script` object compiles `code` but does not run it. The
463-
compiled `vm.Script` can be run later multiple times. The `code` is not bound to
464-
any global object; rather, it is bound before each run, just for that run.
529+
(`module.status` is `'evaluating'`) to prevent infinite recursion.
465530

466-
### script.createCachedData()
467-
<!-- YAML
468-
added: v10.6.0
469-
-->
531+
Corresponds to the [Evaluate() concrete method][] field of [Source Text Module
532+
Record][]s in the ECMAScript specification.
470533

471-
* Returns: {Buffer}
534+
### module.instantiate()
472535

473-
Creates a code cache that can be used with the Script constructor's
474-
`cachedData` option. Returns a Buffer. This method may be called at any
475-
time and any number of times.
536+
Instantiate the module. This must be called after linking has completed
537+
(`linkingStatus` is `'linked'`); otherwise it will throw an error. It may also
538+
throw an exception if one of the dependencies does not provide an export the
539+
parent module requires.
476540

477-
```js
478-
const script = new vm.Script(`
479-
function add(a, b) {
480-
return a + b;
481-
}
541+
However, if this function succeeded, further calls to this function after the
542+
initial instantiation will be no-ops, to be consistent with the ECMAScript
543+
specification.
482544

483-
const x = add(1, 2);
484-
`);
545+
Unlike other methods operating on `Module`, this function completes
546+
synchronously and returns nothing.
485547

486-
const cacheWithoutX = script.createCachedData();
548+
Corresponds to the [Instantiate() concrete method][] field of [Source Text
549+
Module Record][]s in the ECMAScript specification.
487550

488-
script.runInThisContext();
551+
### module.link(linker)
489552

490-
const cacheWithX = script.createCachedData();
491-
```
553+
* `linker` {Function}
554+
* `specifier` {string} The specifier of the requested module:
555+
<!-- eslint-skip -->
556+
```js
557+
import foo from 'foo';
558+
// ^^^^^ the module specifier
559+
```
560+
* `referencingModule` {vm.SourceTextModule} The `Module` object `link()` is
561+
called on.
562+
* Returns: {vm.SourceTextModule|Promise}
563+
* Returns: {Promise}
492564

493-
### script.runInContext(contextifiedSandbox[, options])
494-
<!-- YAML
495-
added: v0.3.1
496-
changes:
497-
- version: v6.3.0
498-
pr-url: https://github.com/nodejs/node/pull/6635
499-
description: The `breakOnSigint` option is supported now.
500-
-->
565+
Link module dependencies. This method must be called before instantiation, and
566+
can only be called once per module.
501567

502-
* `contextifiedSandbox` {Object} A [contextified][] object as returned by the
503-
`vm.createContext()` method.
504-
* `options` {Object}
505-
* `displayErrors` {boolean} When `true`, if an [`Error`][] occurs
506-
while compiling the `code`, the line of code causing the error is attached
507-
to the stack trace. **Default:** `true`.
508-
* `timeout` {integer} Specifies the number of milliseconds to execute `code`
509-
before terminating execution. If execution is terminated, an [`Error`][]
510-
will be thrown. This value must be a strictly positive integer.
511-
* `breakOnSigint` {boolean} If `true`, the execution will be terminated when
512-
`SIGINT` (Ctrl+C) is received. Existing handlers for the
513-
event that have been attached via `process.on('SIGINT')` will be disabled
514-
during script execution, but will continue to work after that. If execution
515-
is terminated, an [`Error`][] will be thrown. **Default:** `false`.
516-
* Returns: {any} the result of the very last statement executed in the script.
568+
The function is expected to return a `Module` object or a `Promise` that
569+
eventually resolves to a `Module` object. The returned `Module` must satisfy the
570+
following two invariants:
517571

518-
Runs the compiled code contained by the `vm.Script` object within the given
519-
`contextifiedSandbox` and returns the result. Running code does not have access
520-
to local scope.
572+
- It must belong to the same context as the parent `Module`.
573+
- Its `linkingStatus` must not be `'errored'`.
521574

522-
The following example compiles code that increments a global variable, sets
523-
the value of another global variable, then execute the code multiple times.
524-
The globals are contained in the `sandbox` object.
575+
If the returned `Module`'s `linkingStatus` is `'unlinked'`, this method will be
576+
recursively called on the returned `Module` with the same provided `linker`
577+
function.
525578

526-
```js
527-
const util = require('util');
528-
const vm = require('vm');
579+
`link()` returns a `Promise` that will either get resolved when all linking
580+
instances resolve to a valid `Module`, or rejected if the linker function either
581+
throws an exception or returns an invalid `Module`.
529582

530-
const sandbox = {
531-
animal: 'cat',
532-
count: 2
533-
};
583+
The linker function roughly corresponds to the implementation-defined
584+
[HostResolveImportedModule][] abstract operation in the ECMAScript
585+
specification, with a few key differences:
534586

535-
const script = new vm.Script('count += 1; name = "kitty";');
587+
- The linker function is allowed to be asynchronous while
588+
[HostResolveImportedModule][] is synchronous.
589+
- The linker function is executed during linking, a Node.js-specific stage
590+
before instantiation, while [HostResolveImportedModule][] is called during
591+
instantiation.
536592

537-
const context = vm.createContext(sandbox);
538-
for (let i = 0; i < 10; ++i) {
539-
script.runInContext(context);
540-
}
593+
The actual [HostResolveImportedModule][] implementation used during module
594+
instantiation is one that returns the modules linked during linking. Since at
595+
that point all modules would have been fully linked already, the
596+
[HostResolveImportedModule][] implementation is fully synchronous per
597+
specification.
541598

542-
console.log(util.inspect(sandbox));
599+
### module.linkingStatus
543600

544-
// { animal: 'cat', count: 12, name: 'kitty' }
545-
```
601+
* {string}
546602

547-
Using the `timeout` or `breakOnSigint` options will result in new event loops
548-
and corresponding threads being started, which have a non-zero performance
549-
overhead.
603+
The current linking status of `module`. It will be one of the following values:
550604

551-
### script.runInNewContext([sandbox[, options]])
552-
<!-- YAML
553-
added: v0.3.1
554-
changes:
555-
- version: v10.0.0
556-
pr-url: https://github.com/nodejs/node/pull/19016
557-
description: The `contextCodeGeneration` option is supported now.
558-
- version: v6.3.0
559-
pr-url: https://github.com/nodejs/node/pull/6635
560-
description: The `breakOnSigint` option is supported now.
561-
-->
605+
- `'unlinked'`: `module.link()` has not yet been called.
606+
- `'linking'`: `module.link()` has been called, but not all Promises returned by
607+
the linker function have been resolved yet.
608+
- `'linked'`: `module.link()` has been called, and all its dependencies have
609+
been successfully linked.
610+
- `'errored'`: `module.link()` has been called, but at least one of its
611+
dependencies failed to link, either because the callback returned a `Promise`
612+
that is rejected, or because the `Module` the callback returned is invalid.
562613

563-
* `sandbox` {Object} An object that will be [contextified][]. If `undefined`, a
564-
new object will be created.
565-
* `options` {Object}
566-
* `displayErrors` {boolean} When `true`, if an [`Error`][] occurs
567-
while compiling the `code`, the line of code causing the error is attached
568-
to the stack trace. **Default:** `true`.
569-
* `timeout` {integer} Specifies the number of milliseconds to execute `code`
570-
before terminating execution. If execution is terminated, an [`Error`][]
571-
will be thrown. This value must be a strictly positive integer.
572-
* `breakOnSigint` {boolean} If `true`, the execution will be terminated when
573-
`SIGINT` (Ctrl+C) is received. Existing handlers for the
574-
event that have been attached via `process.on('SIGINT')` will be disabled
575-
during script execution, but will continue to work after that. If execution
576-
is terminated, an [`Error`][] will be thrown. **Default:** `false`.
577-
* `contextName` {string} Human-readable name of the newly created context.
578-
**Default:** `'VM Context i'`, where `i` is an ascending numerical index of
579-
the created context.
580-
* `contextOrigin` {string} [Origin][origin] corresponding to the newly
581-
created context for display purposes. The origin should be formatted like a
582-
URL, but with only the scheme, host, and port (if necessary), like the
583-
value of the [`url.origin`][] property of a [`URL`][] object. Most notably,
584-
this string should omit the trailing slash, as that denotes a path.
585-
**Default:** `''`.
586-
* `contextCodeGeneration` {Object}
587-
* `strings` {boolean} If set to false any calls to `eval` or function
588-
constructors (`Function`, `GeneratorFunction`, etc) will throw an
589-
`EvalError`. **Default:** `true`.
590-
* `wasm` {boolean} If set to false any attempt to compile a WebAssembly
591-
module will throw a `WebAssembly.CompileError`. **Default:** `true`.
592-
* Returns: {any} the result of the very last statement executed in the script.
614+
### module.namespace
593615

594-
First contextifies the given `sandbox`, runs the compiled code contained by
595-
the `vm.Script` object within the created sandbox, and returns the result.
596-
Running code does not have access to local scope.
616+
* {Object}
597617

598-
The following example compiles code that sets a global variable, then executes
599-
the code multiple times in different contexts. The globals are set on and
600-
contained within each individual `sandbox`.
618+
The namespace object of the module. This is only available after instantiation
619+
(`module.instantiate()`) has completed.
601620

602-
```js
603-
const util = require('util');
604-
const vm = require('vm');
621+
Corresponds to the [GetModuleNamespace][] abstract operation in the ECMAScript
622+
specification.
605623

606-
const script = new vm.Script('globalVar = "set"');
624+
### module.status
607625

608-
const sandboxes = [{}, {}, {}];
609-
sandboxes.forEach((sandbox) => {
610-
script.runInNewContext(sandbox);
611-
});
626+
* {string}
612627

613-
console.log(util.inspect(sandboxes));
628+
The current status of the module. Will be one of:
614629

615-
// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
616-
```
630+
- `'uninstantiated'`: The module is not instantiated. It may because of any of
631+
the following reasons:
617632

618-
### script.runInThisContext([options])
619-
<!-- YAML
620-
added: v0.3.1
621-
changes:
622-
- version: v6.3.0
623-
pr-url: https://github.com/nodejs/node/pull/6635
624-
description: The `breakOnSigint` option is supported now.
625-
-->
633+
- The module was just created.
634+
- `module.instantiate()` has been called on this module, but it failed for
635+
some reason.
626636

627-
* `options` {Object}
628-
* `displayErrors` {boolean} When `true`, if an [`Error`][] occurs
629-
while compiling the `code`, the line of code causing the error is attached
630-
to the stack trace. **Default:** `true`.
631-
* `timeout` {integer} Specifies the number of milliseconds to execute `code`
632-
before terminating execution. If execution is terminated, an [`Error`][]
633-
will be thrown. This value must be a strictly positive integer.
634-
* `breakOnSigint` {boolean} If `true`, the execution will be terminated when
635-
`SIGINT` (Ctrl+C) is received. Existing handlers for the
636-
event that have been attached via `process.on('SIGINT')` will be disabled
637-
during script execution, but will continue to work after that. If execution
638-
is terminated, an [`Error`][] will be thrown. **Default:** `false`.
639-
* Returns: {any} the result of the very last statement executed in the script.
637+
This status does not convey any information regarding if `module.link()` has
638+
been called. See `module.linkingStatus` for that.
640639

641-
Runs the compiled code contained by the `vm.Script` within the context of the
642-
current `global` object. Running code does not have access to local scope, but
643-
*does* have access to the current `global` object.
640+
- `'instantiating'`: The module is currently being instantiated through a
641+
`module.instantiate()` call on itself or a parent module.
644642

645-
The following example compiles code that increments a `global` variable then
646-
executes that code multiple times:
643+
- `'instantiated'`: The module has been instantiated successfully, but
644+
`module.evaluate()` has not yet been called.
647645

648-
```js
649-
const vm = require('vm');
646+
- `'evaluating'`: The module is being evaluated through a `module.evaluate()` on
647+
itself or a parent module.
650648

651-
global.globalVar = 0;
649+
- `'evaluated'`: The module has been successfully evaluated.
652650

653-
const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
651+
- `'errored'`: The module has been evaluated, but an exception was thrown.
654652

655-
for (let i = 0; i < 1000; ++i) {
656-
script.runInThisContext();
657-
}
653+
Other than `'errored'`, this status string corresponds to the specification's
654+
[Source Text Module Record][]'s `[[Status]]` field. `'errored'` corresponds to
655+
`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a
656+
value that is not `undefined`.
658657

659-
console.log(globalVar);
658+
### module.url
660659

661-
// 1000
662-
```
660+
* {string}
661+
662+
The URL of the current module, as set in the constructor.
663663

664664
## vm.compileFunction(code[, params[, options]])
665665
<!-- YAML

0 commit comments

Comments
 (0)
Please sign in to comment.