The following constants are returned as the status field in the object returned by enableCompileCache to indicate the result of the attempt to enable the module compile cache.
Node.js module
module
The 'node:module' module provides utilities for interacting with Node.js's module loading system. You can create custom Module equire functions, inspect module cache, and evaluate code in isolated contexts.
Works in Bun
Core CJS (require) and ESM (import) functionality works. Overriding require.cache is supported. However, `module.register` (for loaders) is not implemented (use Bun plugins). Some Module methods and internal properties (`_extensions`, `_pathCache`, `_cache`) are missing or no-ops.
- namespace constants- namespace compileCacheStatus- The compile cache has already been enabled before, either by a previous call to enableCompileCache, or by the - NODE_COMPILE_CACHE=direnvironment variable. The directory used to store the compile cache will be returned in the- directoryfield in the returned object.
- Node.js cannot enable the compile cache because the environment variable - NODE_DISABLE_COMPILE_CACHE=1has been set.
- Node.js has enabled the compile cache successfully. The directory used to store the compile cache will be returned in the - directoryfield in the returned object.
- 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 - messagefield in the returned object.
 
 
- class SourceMap- lineOffset: number,columnOffset: numberGiven a line offset and column offset in the generated source file, returns an object representing the SourceMap range in the original file if found, or an empty object if not. The object returned contains the following keys: The returned value represents the raw range as it appears in the SourceMap, based on zero-indexed offsets, not 1-indexed line and column numbers as they appear in Error messages and CallSite objects. To get the corresponding 1-indexed line and column numbers from a lineNumber and columnNumber as they are reported by Error stacks and CallSite objects, use sourceMap.findOrigin(lineNumber, columnNumber)@param lineOffsetThe zero-indexed line number offset in the generated source @param columnOffsetThe zero-indexed column number offset in the generated source 
- lineNumber: number,columnNumber: numberGiven a 1-indexed lineNumberandcolumnNumberfrom a call site in the generated source, find the corresponding call site location in the original source.If the lineNumberandcolumnNumberprovided are not found in any source map, then an empty object is returned.@param lineNumberThe 1-indexed line number of the call site in the generated source @param columnNumberThe 1-indexed column number of the call site in the generated source 
 
- interface EnableCompileCacheResult- directory?: stringIf the compile cache is enabled, this contains the directory where the compile cache is stored. Only set if statusismodule.constants.compileCacheStatus.ENABLEDormodule.constants.compileCacheStatus.ALREADY_ENABLED.
- message?: stringIf Node.js cannot enable the compile cache, this contains the error message. Only set if statusismodule.constants.compileCacheStatus.FAILED.
 
- interface ImportAttributes
- interface LoadFnOutput
- interface LoadHookContext- format: undefined | null | stringThe format optionally supplied by the resolvehook chain (can be an intermediary value).
- importAttributes: ImportAttributesAn object whose key-value pairs represent the assertions for the module to import 
 
- interface ModuleHooks- Deregister the hook instance. 
 
- interface RegisterHooksOptions
- interface RegisterOptions<Data>
- interface ResolveFnOutput- importAttributes?: ImportAttributesThe import attributes to use when caching the module (optional; if excluded the input will be used) 
 
- interface ResolveHookContext- importAttributes: ImportAttributesAn object whose key-value pairs represent the assertions for the module to import 
- parentURL: undefined | stringThe module importing this one, or undefined if this is the Node.js entry point 
 
- interface SetSourceMapsSupportOptions
- interface SourceMapConstructorOptions
- interface SourceMapPayload
- interface SourceMapping
- interface SourceMapsSupport
- interface SourceOrigin- columnNumber: numberThe 1-indexed columnNumber of the corresponding call site in the original source 
 
- interface StripTypeScriptTypesOptions- mode?: 'strip' | 'transform'Possible values are: - 'strip'Only strip type annotations without performing the transformation of TypeScript features.
- 'transform'Strip type annotations and transform TypeScript features to JavaScript.
 
- sourceMap?: booleanOnly when modeis'transform', iftrue, a source map will be generated for the transformed code.
 
- type ImportPhase = 'source' | 'evaluation'
- type InitializeHook<Data = any> = (data: Data) => void | Promise<void>The initializehook provides a way to define a custom function that runs in the hooks thread when the hooks module is initialized. Initialization happens when the hooks module is registered via register.This hook can receive data from a register invocation, including ports and other transferable objects. The return value of initializecan be aPromise, in which case it will be awaited before the main application thread execution resumes.
- type LoadHook = (url: string, context: LoadHookContext, nextLoad: (url: string, context?: Partial<LoadHookContext>) => LoadFnOutput | Promise<LoadFnOutput>) => LoadFnOutput | Promise<LoadFnOutput>The loadhook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. It is also in charge of validating the import attributes.
- type LoadHookSync = (url: string, context: LoadHookContext, nextLoad: (url: string, context?: Partial<LoadHookContext>) => LoadFnOutput) => LoadFnOutput
- type ModuleFormat = 'addon' | 'builtin' | 'commonjs' | 'commonjs-typescript' | 'json' | 'module' | 'module-typescript' | 'wasm'
- type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray
- type ResolveHook = (specifier: string, context: ResolveHookContext, nextResolve: (specifier: string, context?: Partial<ResolveHookContext>) => ResolveFnOutput | Promise<ResolveFnOutput>) => ResolveFnOutput | Promise<ResolveFnOutput>The resolvehook chain is responsible for telling Node.js where to find and how to cache a givenimportstatement or expression, orrequirecall. It can optionally return a format (such as'module') as a hint to theloadhook. If a format is specified, theloadhook is ultimately responsible for providing the finalformatvalue (and it is free to ignore the hint provided byresolve); ifresolveprovides aformat, a customloadhook is required even if only to pass the value to the Node.js defaultloadhook.
- type ResolveHookSync = (specifier: string, context: ResolveHookContext, nextResolve: (specifier: string, context?: Partial<ResolveHookContext>) => ResolveFnOutput) => ResolveFnOutput
- A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not. - Note: the list doesn't contain prefix-only modules like - node:test.
- @param pathFilename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string. 
- cacheDir?: stringEnable module compile cache in the current Node.js instance. If cacheDiris not specified, Node.js will either use the directory specified by theNODE_COMPILE_CACHE=direnvironment variable if it's set, or usepath.join(os.tmpdir(), 'node-compile-cache')otherwise. For general use cases, it's recommended to callmodule.enableCompileCache()without specifying thecacheDir, so that the directory can be overridden by theNODE_COMPILE_CACHEenvironment variable when necessary.Since compile cache is supposed to be a quiet optimization that is not required for the application to be functional, 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 messagefield to aid debugging. If compile cache is enabled successfully, thedirectoryfield in the returned object contains the path to the directory where the compile cache is stored. Thestatusfield in the returned object would be one of themodule.constants.compileCacheStatusvalues 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_CACHEvalue to compile cache directory so the behavior can be inherited into the child workers. The directory can be obtained either from thedirectoryfield returned by this method, or with getCompileCacheDir.@param cacheDirOptional path to specify the directory where the compile cache will be stored/retrieved. 
- ): undefined | string;/path/to/project ├ packages/ ├ bar/ ├ bar.js └ package.json // name = '@foo/bar' └ qux/ ├ node_modules/ └ some-package/ └ package.json // name = 'some-package' ├ qux.js └ package.json // name = '@foo/qux' ├ main.js └ package.json // name = '@foo'// /path/to/project/packages/bar/bar.js import { findPackageJSON } from 'node:module'; findPackageJSON('..', import.meta.url); // '/path/to/project/package.json' // Same result when passing an absolute specifier instead: findPackageJSON(new URL('../', import.meta.url)); findPackageJSON(import.meta.resolve('../')); findPackageJSON('some-package', import.meta.url); // '/path/to/project/packages/bar/node_modules/some-package/package.json' // When passing an absolute specifier, you might get a different result if the // resolved module is inside a subfolder that has nested `package.json`. findPackageJSON(import.meta.resolve('some-package')); // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' findPackageJSON('@foo/qux', import.meta.url); // '/path/to/project/packages/qux/package.json'@param specifierThe specifier for the module whose package.jsonto retrieve. When passing a bare specifier, thepackage.jsonat the root of the package is returned. When passing a relative specifier or an absolute specifier, the closest parentpackage.jsonis returned.@param baseThe absolute location ( file:URL string or FS path) of the containing module. For CJS, use__filename(not__dirname!); for ESM, useimport.meta.url. You do not need to pass it ifspecifieris an absolute specifier.@returnsA path if the package.jsonis found. WhenstartLocationis a package, the package's rootpackage.json; when a relative or unresolved, the closestpackage.jsonto thestartLocation.
- path: stringpathis the resolved path for the file for which a corresponding source map should be fetched.@returnsReturns module.SourceMapif a source map is found,undefinedotherwise.
- 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. 
- @returnsPath to the module compile cache directory if it is enabled, or undefinedotherwise.
- This method returns whether the Source Map v3 support for stack traces is enabled. 
- ): void;Register a module that exports hooks that customize Node.js module resolution and loading behavior. See Customization hooks. This feature requires --allow-workerif used with the Permission Model.@param specifierCustomization hooks to be registered; this should be the same string that would be passed to import(), except that if it is relative, it is resolved relative toparentURL.@param parentURLf you want to resolve specifierrelative to a base URL, such asimport.meta.url, you can pass that URL here.): void;Register a module that exports hooks that customize Node.js module resolution and loading behavior. See Customization hooks. This feature requires --allow-workerif used with the Permission Model.@param specifierCustomization hooks to be registered; this should be the same string that would be passed to import(), except that if it is relative, it is resolved relative toparentURL.
- Register hooks that customize Node.js module resolution and loading behavior. 
- enabled: boolean,): void;This function enables or disables the Source Map v3 support for stack traces. It provides same features as launching Node.js process with commandline options --enable-source-maps, with additional options to alter the support for files innode_modulesor generated codes.Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. Preferably, use the commandline options --enable-source-mapsto avoid losing track of source maps of modules loaded before this API call.
- code: string,): string;module.stripTypeScriptTypes()removes type annotations from TypeScript code. It can be used to strip type annotations from TypeScript code before running it withvm.runInContext()orvm.compileFunction(). By default, it will throw an error if the code contains TypeScript features that require transformation such asEnums, see type-stripping for more information. When mode is'transform', it also transforms TypeScript features to JavaScript, see transform TypeScript features for more information. When mode is'strip', source maps are not generated, because locations are preserved. IfsourceMapis provided, when mode is'strip', an error will be thrown.WARNING: The output of this function should not be considered stable across Node.js versions, due to changes in the TypeScript parser. import { stripTypeScriptTypes } from 'node:module'; const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code); console.log(strippedCode); // Prints: const a = 1;If sourceUrlis provided, it will be used appended as a comment at the end of the output:import { stripTypeScriptTypes } from 'node:module'; const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); console.log(strippedCode); // Prints: const a = 1\n\n//# sourceURL=source.ts;When modeis'transform', the code is transformed to JavaScript:import { stripTypeScriptTypes } from 'node:module'; const code = ` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`; const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); console.log(strippedCode); // Prints: // var MathUtil; // (function(MathUtil) { // MathUtil.add = (a, b)=>a + b; // })(MathUtil || (MathUtil = {})); // # sourceMappingURL=data:application/json;base64, ...@param codeThe code to strip type annotations from. @returnsThe code with type annotations stripped. 
- The - module.syncBuiltinESMExports()method updates all the live bindings for builtin- ES Modulesto match the properties of the- CommonJSexports. It does not add or remove exported names from the- ES Modules.- import fs from 'node:fs'; import assert from 'node:assert'; import { syncBuiltinESMExports } from 'node:module'; fs.readFile = newAPI; delete fs.readFileSync; function newAPI() { // ... } fs.newAPI = newAPI; syncBuiltinESMExports(); import('node:fs').then((esmFS) => { // It syncs the existing readFile property with the new value assert.strictEqual(esmFS.readFile, newAPI); // readFileSync has been deleted from the required fs assert.strictEqual('readFileSync' in fs, false); // syncBuiltinESMExports() does not remove readFileSync from esmFS assert.strictEqual('readFileSync' in esmFS, true); // syncBuiltinESMExports() does not add names assert.strictEqual(esmFS.newAPI, undefined); });
 
- class default- exports: anyThe module.exportsobject is created by theModulesystem. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object tomodule.exports.
- path: stringThe directory name of the module. This is usually the same as the path.dirname()of themodule.id.
- id: string): any;The module.require()method provides a way to load a module as ifrequire()was called from the original module.