Skip to content

Commit

Permalink
doc: fix vm.Script createCachedData example
Browse files Browse the repository at this point in the history
`Script.createCachedData` and `SourceTextModule.createCachedData`
doesn't serialize JavaScript variables.
  • Loading branch information
legendecas committed Sep 2, 2022
1 parent d0f73d3 commit 77bd10c
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions doc/api/vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@ Creates a code cache that can be used with the `Script` constructor's
`cachedData` option. Returns a `Buffer`. This method may be called at any
time and any number of times.

The code cache of the `Script` doesn't contain any JavaScript observable
states. The code cache is safe to be saved along side the script source and
used to construct new `Script` instances multiple times.

Functions in the `Script` source can be marked as lazily compiled and they are
not compiled at construction of the `Script`. These functions are forced to be
compiled when they are invoked the first time. The code cache serializes the
current compilation state.

```js
const script = new vm.Script(`
function add(a, b) {
Expand All @@ -135,11 +144,13 @@ function add(a, b) {
const x = add(1, 2);
`);

const cacheWithoutX = script.createCachedData();
const cache1 = script.createCachedData();
// cached1 contains function `add` with lazy compilation stub.

script.runInThisContext();

const cacheWithX = script.createCachedData();
const cache2 = script.createCachedData();
// cached2 contains compiled function `add`.
```

### `script.runInContext(contextifiedObject[, options])`
Expand Down Expand Up @@ -780,6 +791,15 @@ Creates a code cache that can be used with the `SourceTextModule` constructor's
`cachedData` option. Returns a `Buffer`. This method may be called any number
of times before the module has been evaluated.

The code cache of the `SourceTextModule` doesn't contain any JavaScript
observable states. The code cache is safe to be saved along side the script
source and used to construct new `SourceTextModule` instances multiple times.
Functions in the `SourceTextModule` source can be marked as lazily compiled and
they are not compiled at construction of the `SourceTextModule`. These
functions are forced to be compiled when they are invoked the first time. The
code cache serializes the current compilation state.
```js
// Create an initial module
const module = new vm.SourceTextModule('const a = 1;');
Expand Down

0 comments on commit 77bd10c

Please sign in to comment.