On this page

Module compile cache

History

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, an 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.

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 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().

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).

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.

The compile cache layout on disk is an implementation detail and should not be relied upon. The compile cache generated is typically only reusable in the same version of Node.js, and should be not assumed to be compatible across different versions of Node.js.

By default, caches are invalidated when the absolute paths of the modules being cached are changed. To keep the cache working after moving the project directory, enable portable compile cache. This allows previously compiled modules to be reused across different directory locations as long as the layout relative to the cache directory remains the same. This would be done on a best-effort basis. If Node.js cannot compute the location of a module relative to the cache directory, the module will not be cached.

A portable cache is also not split by user: on platforms with uids the cache subdirectory of a non-portable cache is suffixed with the uid of the user who created it, so it is only found by that user, while a portable cache uses the same subdirectory for every user. This lets a cache generated once (for example at build time, then shipped read-only with an application) be read by whoever runs the code; a user who cannot write to the directory still reads it, and a failed write only means the module is compiled again.

There are two ways to enable the portable mode:

  1. Using the portable option in module.enableCompileCache():

    // Non-portable cache (default): cache breaks if project is moved
    module.enableCompileCache({ directory: '/path/to/cache/storage/dir' });
    
    // Portable cache: cache works after the project is moved
    module.enableCompileCache({ directory: '/path/to/cache/storage/dir', portable: true });
  2. Setting the environment variable: NODE_COMPILE_CACHE_PORTABLE=1

A cache that was generated ahead of time, for example at build time to be shipped inside an application package, can be enabled with readOnly: true (or NODE_COMPILE_CACHE_READONLY=1). Node.js then loads whatever entries the directory holds and never writes to it: modules without a usable entry are compiled as usual but not persisted, module.flushCompileCache() is a no-op, and the directory is not created if it is missing.

Currently when using the compile cache with V8 JavaScript code coverage, the coverage being collected by V8 may be less precise in functions that are deserialized from the code cache. It's recommended to turn this off when running tests to generate precise coverage.

Compilation cache generated by one version of Node.js can not be reused by a different version of Node.js. Cache generated by different versions of Node.js will be stored separately if the same base directory is used to persist the cache, so they can co-exist.

The following constants are returned as the status field in the object returned by module.enableCompileCache() to indicate the result of the attempt to enable the module compile cache.

Constant Description
ENABLED Node.js has enabled the compile cache successfully. The directory used to store the compile cache will be returned in the directory field in the returned object.
ALREADY_ENABLED The compile cache has already been enabled before, either by a previous call to module.enableCompileCache(), or by the NODE_COMPILE_CACHE=dir environment variable. The directory used to store the compile cache will be returned in the directory field in the returned object.
FAILED Node.js fails to enable the compile cache. This can be caused by the lack of permission to use the specified directory, or various kinds of file system errors. The detail of the failure will be returned in the message field in the returned object.
DISABLED Node.js cannot enable the compile cache because the environment variable NODE_DISABLE_COMPILE_CACHE=1 has been set.
module.enableCompileCache(options?): Object
Attributes
options:string | Object
Optional. If a string is passed, it is considered to be options.directory.
directory:string
Optional. Directory to store the compile cache. If not specified, the directory specified by the NODE_COMPILE_CACHE=dir environment variable will be used if it's set, or path.join(os.tmpdir(), 'node-compile-cache') otherwise.
portable:boolean
Optional. If true, enables portable compile cache so that the cache can be reused even if the project directory is moved. This is a best-effort feature. If not specified, it will depend on whether the environment variable NODE_COMPILE_CACHE_PORTABLE=1 is set.
readOnly:boolean
Optional. If true, existing cache entries in directory are used but nothing is ever written to it, and the directory is not created when it does not exist (enabling then fails). Meant for caches generated ahead of time and shipped with an application. If not specified, it will depend on whether the environment variable NODE_COMPILE_CACHE_READONLY=1 is set.
Returns:Object
message:string | undefined
If Node.js cannot enable the compile cache, this contains the error message. Only set if status is module.constants.compileCacheStatus.FAILED.
directory:string | undefined
If the compile cache is enabled, this contains the directory where the compile cache is stored. Only set if status is module.constants.compileCacheStatus.ENABLED or module.constants.compileCacheStatus.ALREADY_ENABLED.

Enable module compile cache in the current Node.js instance.

For general use cases, it's recommended to call module.enableCompileCache() without specifying the options.directory, so that the directory can be overridden by the NODE_COMPILE_CACHE environment variable when necessary.

Since compile cache is supposed to be an optimization that is not mission critical, this method is designed to not throw any exception when the compile cache cannot be enabled. Instead, it will return an object containing an error message in the message field to aid debugging. If compile cache is enabled successfully, the directory field in the returned object contains the path to the directory where the compile cache is stored. The status field in the returned object would be one of the module.constants.compileCacheStatus values to indicate the result of the attempt to enable the module compile cache.

This method only affects the current Node.js instance. To enable it in child worker threads, either call this method in child worker threads too, or set the process.env.NODE_COMPILE_CACHE value to compile cache directory so the behavior can be inherited into the child workers. The directory can be obtained either from the directory field returned by this method, or with module.getCompileCacheDir().

M

module.flushCompileCache

History
module.flushCompileCache(): void

Flush the module compile cache accumulated from modules already loaded in the current Node.js instance to disk. This returns after all the flushing file system operations come to an end, no matter they succeed or not. If there are any errors, this will fail silently, since compile cache misses should not interfere with the actual operation of the application.

module.getCompileCacheDir(): string | undefined
Returns:string | undefined
Path to the module compile cache directory if it is enabled, or undefined otherwise.