From f54cb3baa5b8b72c07b53a1d5b6447c3f11366a8 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 4 Sep 2024 20:18:12 +0200 Subject: [PATCH] module: implement flushCompileCache() This implements an API for users to intentionally flush the accumulated compile cache instead of waiting until process shutdown. It may be useful for application that loads dependencies first and then either reload itself in other instances, or spawning other instances that load an overlapping set of its dependencies - in this case its useful to flush the cache early instead of waiting until the shutdown of itself. Currently flushing is triggered by either process shutdown or user requests. In the future we should simply start the writes right after module loading on a separate thread, and this method only blocks until all the pending writes (if any) on the other thread are finished. In that case, the off-thread writes should finish long before any attempt of flushing is made so the method would then only incur a negligible overhead from thread synchronization. --- doc/api/module.md | 22 +++++++++ lib/internal/modules/helpers.js | 2 + lib/module.js | 3 ++ src/compile_cache.cc | 7 +++ src/node_modules.cc | 16 +++++++ test/fixtures/compile-cache-flush.js | 21 +++++++++ test/parallel/test-compile-cache-api-flush.js | 47 +++++++++++++++++++ 7 files changed, 118 insertions(+) create mode 100644 test/fixtures/compile-cache-flush.js create mode 100644 test/parallel/test-compile-cache-api-flush.js diff --git a/doc/api/module.md b/doc/api/module.md index 3bb25c3f313da1..7e4e1116789311 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -1101,6 +1101,28 @@ added: `path` is the resolved path for the file for which a corresponding source map should be fetched. +### `module.flushCompileCache([keepDeserializedCache])` + + + +> Stability: 1.1 - Active Development + +* `keepDeserializedCache` {boolean} Whether the cache read from disk and already deserialized to + compile the corresponding modules should be kept after flushing. + Defaults to `false`. + +Flush the [module compile cache][] accumulated from loaded modules to disk. + +In most cases, it's not necessary to set the `keepDeserializedCache` option. After a module +is compiled, there is another tier of module cache in Node.js, so keeping the code cache that +is already deserialized into a live module usually just increases memory usage for no +additional benefit. It's only useful if users intentionally purge the live cache e.g. +by deleting from `require.cache` while expecting most source code to still remain unchanged +and can be recompiled using the cache already read from disk. + ### Class: `module.SourceMap`