script.createCachedData()


创建一个代码缓存,可用于 Script 构造函数的 cachedData 选项。返回一个 Buffer。此方法可以在任何时间、调用任意次数。

【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.】

Script 的代码缓存不包含任何可被 JavaScript 观察的状态。代码缓存可以安全地与脚本源一起保存,并可多次用来构建新的 Script 实例。

【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.】

Script 源中的函数可以被标记为延迟编译,它们在构建 Script 时不会被编译。这些函数会在第一次被调用时进行编译。代码缓存会序列化 V8 当前已知的关于 Script 的元数据,这些元数据可以用来加速未来的编译。

【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.】

const script = new vm.Script(`
function add(a, b) {
  return a + b;
}

const x = add(1, 2);
`);

const cacheWithoutAdd = script.createCachedData();
// In `cacheWithoutAdd` the function `add()` is marked for full compilation
// upon invocation.

script.runInThisContext();

const cacheWithAdd = script.createCachedData();
// `cacheWithAdd` contains fully compiled function `add()`.