From 48d944b71cc553a376c608e059ada64354493fe0 Mon Sep 17 00:00:00 2001 From: Chengzhong Wu Date: Mon, 12 Sep 2022 16:23:53 +0800 Subject: [PATCH] doc: fix vm.Script createCachedData example `Script.createCachedData` and `SourceTextModule.createCachedData` doesn't serialize JavaScript variables. PR-URL: https://github.com/nodejs/node/pull/44487 Reviewed-By: Joyee Cheung --- doc/api/vm.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/doc/api/vm.md b/doc/api/vm.md index ea8d46512857cf..f99f4966db82b6 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -138,6 +138,16 @@ 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 going to be +compiled when they are invoked the first time. The code cache serializes the +metadata that V8 currently knows about the `Script` that it can use to speed up +future compilations. + ```js const script = new vm.Script(` function add(a, b) { @@ -147,11 +157,14 @@ function add(a, b) { const x = add(1, 2); `); -const cacheWithoutX = script.createCachedData(); +const cacheWithoutAdd = script.createCachedData(); +// In `cacheWithoutAdd` the function `add()` is marked for full compilation +// upon invocation. script.runInThisContext(); -const cacheWithX = script.createCachedData(); +const cacheWithAdd = script.createCachedData(); +// `cacheWithAdd` contains fully compiled function `add()`. ``` ### `script.runInContext(contextifiedObject[, options])` @@ -792,6 +805,16 @@ 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 going to be compiled when they are invoked the first time. The +code cache serializes the metadata that V8 currently knows about the +`SourceTextModule` that it can use to speed up future compilations. + ```js // Create an initial module const module = new vm.SourceTextModule('const a = 1;');