林一二2022年12月15日 19:09
一般直接装v8-compile-cache-lib这个库就行了,它会在代码第一次执行时生成缓存,让之后的执行快很多。
原理关键在于用 VM 模块的 produceCachedData 生成缓存:
var script = new vm.Script(wrapper, {
filename: filename,
lineOffset: 0,
displayErrors: true,
cachedData: buffer,
produceCachedData: true,
});
if (script.cachedDataProduced) {
this._cacheStore.set(filename, invalidationKey, script.cachedData);
} else if (script.cachedDataRejected) {
this._cacheStore.delete(filename);
}
详见 NodeJS 文档:
produceCachedData<boolean>: When true and no cachedData is present, V8 will attempt to produce code cache data for code. Upon success, a Buffer with V8's code cache data will be produced and stored in the cachedData property of the returned vm.Script instance. The cachedDataProduced value will be set to either true or false depending on whether code cache data is produced successfully. This option is deprecated in favor ofscript.createCachedData(). Default:false.