模块编译缓存


【Module compile cache】

模块编译缓存可以通过 module.enableCompileCache() 方法或 NODE_COMPILE_CACHE=dir 环境变量启用。启用后,每当 Node.js 编译 CommonJS、ECMAScript 模块或 TypeScript 模块时,它将使用指定目录中持久化在磁盘上的 V8 代码缓存 来加速编译。这可能会减慢模块图的首次加载速度,但如果模块内容没有变化,后续加载同一模块图时可能会获得显著的加速。

【The module compile cache can be enabled either using the module.enableCompileCache() method or the NODE_COMPILE_CACHE=dir environment variable. After it is enabled, whenever Node.js compiles a CommonJS, a ECMAScript Module, or a TypeScript module, it will use on-disk V8 code cache persisted in the specified directory to speed up the compilation. This may slow down the first load of a module graph, but subsequent loads of the same module graph may get a significant speedup if the contents of the modules do not change.】

要清理磁盘上生成的编译缓存,只需删除缓存目录。下次在相同目录中用于编译缓存存储时,该缓存目录将会被重新创建。为避免磁盘被过时的缓存占满,建议使用 os.tmpdir() 下的目录。如果通过调用 module.enableCompileCache() 启用编译缓存而未指定 directory,Node.js 将使用 NODE_COMPILE_CACHE=dir 环境变量(如果已设置),否则默认使用 path.join(os.tmpdir(), 'node-compile-cache')。要查找正在运行的 Node.js 实例使用的编译缓存目录,请使用 module.getCompileCacheDir()

【To clean up the generated compile cache on disk, simply remove the cache directory. The cache directory will be recreated the next time the same directory is used for for compile cache storage. To avoid filling up the disk with stale cache, it is recommended to use a directory under the os.tmpdir(). If the compile cache is enabled by a call to module.enableCompileCache() without specifying the directory, Node.js will use the NODE_COMPILE_CACHE=dir environment variable if it's set, or defaults to path.join(os.tmpdir(), 'node-compile-cache') otherwise. To locate the compile cache directory used by a running Node.js instance, use module.getCompileCacheDir().】

启用的模块编译缓存可以通过 NODE_DISABLE_COMPILE_CACHE=1 环境变量禁用。当编译缓存导致意外或不希望出现的行为(例如测试覆盖率不够精确)时,这可能会很有用。

【The enabled module compile cache can be disabled by the NODE_DISABLE_COMPILE_CACHE=1 environment variable. This can be useful when the compile cache leads to unexpected or undesired behaviors (e.g. less precise test coverage).】

目前,当启用编译缓存并重新加载模块时,代码缓存会立即从已编译的代码生成,但只有在 Node.js 实例即将退出时才会写入磁盘。这可能会有所变化。可以使用 module.flushCompileCache() 方法来确保已累积的代码缓存被刷新到磁盘,以防应用希望生成其他 Node.js 实例,并让它们在父进程退出很久之前就共享缓存。

【At the moment, when the compile cache is enabled and a module is loaded afresh, the code cache is generated from the compiled code immediately, but will only be written to disk when the Node.js instance is about to exit. This is subject to change. The module.flushCompileCache() method can be used to ensure the accumulated code cache is flushed to disk in case the application wants to spawn other Node.js instances and let them share the cache long before the parent exits.】