### Get Module Resolution Paths with require.resolve.paths (Node.js) Source: https://nodejs.org/api/modules.html/index Explains how to use require.resolve.paths to retrieve the array of paths searched during module resolution for a given request. Returns null if the request is for a core module. ```javascript // Example usage (assuming 'some-module' exists) // const paths = require.resolve.paths('some-module'); // console.log(paths); ``` -------------------------------- ### Node.js node_modules Resolution Source: https://nodejs.org/api/modules.html/index When a module identifier is not a built-in module and doesn't start with '/', './', or '../', Node.js searches for it in node_modules directories, starting from the current module's directory and moving up to the root of the file system. ```javascript require('bar.js'); // Searches in /home/ry/projects/node_modules, /home/ry/node_modules, etc. ``` -------------------------------- ### Node.js Mandatory 'node:' Prefix Modules Source: https://nodejs.org/api/modules.html/index Certain built-in Node.js modules require the 'node:' prefix when loaded via require(). This is to avoid naming conflicts with existing user packages. Examples include 'node:sea', 'node:sqlite', 'node:test', and 'node:test/reporters'. ```javascript const sea = require('node:sea'); const testReporters = require('node:test/reporters'); ``` -------------------------------- ### require.main Source: https://nodejs.org/api/modules.html/index The require.main property holds the `Module` object representing the entry script that launched the Node.js process. ```APIDOC ## require.main ### Description Represents the entry script loaded when the Node.js process launched. It is `undefined` if the entry point is not a CommonJS module. ### Added in v0.1.17 ### Type ` | ` ### Example ```javascript // In entry.js console.log(require.main); ``` When run with `node entry.js`, the output will be similar to: ``` Module { id: '.', path: '/absolute/path/to', exports: {}, filename: '/absolute/path/to/entry.js', loaded: false, children: [], paths: [ '/absolute/path/to/node_modules', '/absolute/path/node_modules', '/absolute/node_modules', '/node_modules' ] } ``` ``` -------------------------------- ### Loading and Using a CommonJS Module Exporting a Class in Node.js Source: https://nodejs.org/api/modules.html/index Demonstrates how to load a module that exports a class (`Square`) using `require()` and then instantiate and use that class. This pattern is common for object-oriented programming within Node.js modules. ```javascript const Square = require('./square.js'); const mySquare = new Square(2); console.log(`The area of mySquare is ${mySquare.area()}`); ``` -------------------------------- ### Node.js File Loading Logic Source: https://nodejs.org/api/modules.html/index This pseudocode details the LOAD_AS_FILE function, responsible for loading a module when it's identified as a file. It handles different file extensions (.js, .json, .node) and respects the 'type' field in package.json. ```pseudocode LOAD_AS_FILE(X) 1. If X is a file, load X as its file extension format. STOP 2. If X.js is a file, a. Find the closest package scope SCOPE to X. b. If no scope was found 1. MAYBE_DETECT_AND_LOAD(X.js) c. If the SCOPE/package.json contains "type" field, 1. If the "type" field is "module", load X.js as an ECMAScript module. STOP. 2. If the "type" field is "commonjs", load X.js as a CommonJS module. STOP. d. MAYBE_DETECT_AND_LOAD(X.js) 3. If X.json is a file, load X.json to a JavaScript Object. STOP 4. If X.node is a file, load X.node as binary addon. STOP ``` -------------------------------- ### Loading and Using a CommonJS Module in Node.js Source: https://nodejs.org/api/modules.html/index Demonstrates how to load another module (`circle.js`) using `require()` and then use its exported functions. This is a fundamental pattern for organizing code in Node.js applications. ```javascript const circle = require('./circle.js'); console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); ``` -------------------------------- ### Node.js Directory Loading Logic Source: https://nodejs.org/api/modules.html/index This pseudocode describes the LOAD_AS_DIRECTORY function, which handles module resolution when the path points to a directory. It prioritizes the 'main' field in package.json and falls back to loading an index file. ```pseudocode LOAD_AS_DIRECTORY(X) 1. If X/package.json is a file, a. Parse X/package.json, and look for "main" field. b. If "main" is a falsy value, GOTO 2. c. let M = X + (json main field) d. LOAD_AS_FILE(M) e. LOAD_INDEX(M) f. LOAD_INDEX(X) DEPRECATED g. THROW "not found" 2. LOAD_INDEX(X) ``` -------------------------------- ### Handle Custom File Extensions with require.extensions (Node.js - Deprecated) Source: https://nodejs.org/api/modules.html/index Shows how to register custom file extensions with require.extensions to process them as JavaScript files. This feature is deprecated and should be avoided due to potential bugs and performance degradation. Consider alternative module loading strategies. ```javascript require.extensions['.sjs'] = require.extensions['.js']; ``` -------------------------------- ### Access Main Module with require.main (Node.js) Source: https://nodejs.org/api/modules.html/index Illustrates how to access the Module object representing the entry script of a Node.js process using require.main. This is useful for identifying the main script when it's a CommonJS module. ```javascript console.log(require.main); ``` ```bash node entry.js ``` ```json Module { id: '.', path: '/absolute/path/to', exports: {}, filename: '/absolute/path/to/entry.js', loaded: false, children: [], paths: [ '/absolute/path/to/node_modules', '/absolute/path/node_modules', '/absolute/node_modules', '/node_modules' ] } ``` -------------------------------- ### Exporting Module Instance with module.exports (Node.js) Source: https://nodejs.org/api/modules.html/index Shows how to export an instance of a class or a specific object by assigning it directly to module.exports. This is necessary when a module needs to be more than just a collection of properties. Assignment must be immediate and not in callbacks. ```javascript const EventEmitter = require('node:events'); module.exports = new EventEmitter(); // Do some work, and after some time emit // the 'ready' event from the module itself. setTimeout(() => { module.exports.emit('ready'); }, 1000); ``` ```javascript const a = require('./a'); a.on('ready', () => { console.log('module "a" is ready'); }); ``` ```javascript // This assignment in a callback will not work as expected: // setTimeout(() => { // module.exports = { a: 'hello' }; // }, 0); ``` -------------------------------- ### Loading ESM with .mjs extension using require() Source: https://nodejs.org/api/modules.html/index Demonstrates loading an ECMAScript module with a .mjs extension using the synchronous require() function in a CommonJS module. The module namespace object is returned, similar to dynamic import(). ```javascript // distance.mjs export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); } ``` ```javascript // point.mjs export default class Point { constructor(x, y) { this.x = x; this.y = y; } } ``` ```javascript const distance = require('./distance.mjs'); console.log(distance); // [Module: null prototype] { distance: [Function: distance] } const point = require('./point.mjs'); console.log(point); // [Module: null prototype] { // default: [class Point], // __esModule: true, // } ``` -------------------------------- ### Node.js Built-in Module Loading Source: https://nodejs.org/api/modules.html/index Node.js includes several built-in modules that are compiled into the binary. These can be loaded directly or with the 'node:' prefix. Using the 'node:' prefix guarantees that the built-in module is loaded, bypassing the cache and preventing conflicts with user-land packages. ```javascript // Loading built-in modules const http = require('http'); // Loads built-in HTTP module const fs = require('node:fs'); // Loads built-in FS module with 'node:' prefix ``` -------------------------------- ### Node.js require() Resolution Algorithm Source: https://nodejs.org/api/modules.html/index This pseudocode details the high-level algorithm for Node.js's require() function. It outlines the sequence of checks performed to locate and load modules, including core modules, relative paths, and Node.js modules. ```pseudocode require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with '/' a. set Y to the file system root 3. If X is equal to '.', or X begins with './', '/' or '../' a. LOAD_AS_FILE(Y + X) b. LOAD_AS_DIRECTORY(Y + X) c. THROW "not found" 4. If X begins with '#' a. LOAD_PACKAGE_IMPORTS(X, dirname(Y)) 5. LOAD_PACKAGE_SELF(X, dirname(Y)) 6. LOAD_NODE_MODULES(X, dirname(Y)) 7. THROW "not found" ``` -------------------------------- ### Node.js Index Loading Logic Source: https://nodejs.org/api/modules.html/index This pseudocode outlines the LOAD_INDEX function, used when a directory is specified as the module path. It attempts to load index files (.js, .json, .node) within that directory, respecting package.json types. ```pseudocode LOAD_INDEX(X) 1. If X/index.js is a file a. Find the closest package scope SCOPE to X. b. If no scope was found, load X/index.js as a CommonJS module. STOP. c. If the SCOPE/package.json contains "type" field, 1. If the "type" field is "module", load X/index.js as an ECMAScript module. STOP. 2. Else, load X/index.js as a CommonJS module. STOP. 2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP 3. If X/index.node is a file, load X/index.node as binary addon. STOP ``` -------------------------------- ### require.extensions Source: https://nodejs.org/api/modules.html/index The require.extensions object is used to instruct `require` on how to handle specific file extensions. However, it is deprecated and should be avoided. ```APIDOC ## require.extensions ### Description Instruct `require` on how to handle certain file extensions. This feature is deprecated and should be avoided. ### Added in v0.3.0 ### Deprecated since v0.10.6 ### Type `` ### Example ```javascript // Process files with the extension '.sjs' as '.js' require.extensions['.sjs'] = require.extensions['.js']; ``` ### Warning Avoid using `require.extensions`. It can cause subtle bugs and slow down extension resolution. ``` -------------------------------- ### Resolve Module Path with require.resolve (Node.js) Source: https://nodejs.org/api/modules.html/index Demonstrates using require.resolve to find the location of a module without loading it. It can optionally take an 'options' object with a 'paths' array to specify custom resolution paths. Throws MODULE_NOT_FOUND if the module is not found. ```javascript // Example usage (assuming 'some-module' exists) // const resolvedPath = require.resolve('some-module'); // console.log(resolvedPath); ``` -------------------------------- ### Node.js Path Resolution for Modules Source: https://nodejs.org/api/modules.html/index Modules prefixed with '/' are absolute paths. Modules prefixed with './' or '../' are relative to the calling file. Modules without such prefixes are treated as core modules or loaded from node_modules. ```javascript require('/home/marco/foo.js'); // Absolute path require('./circle'); // Relative path require('fs'); // Core module or node_modules ``` -------------------------------- ### Node.js Module Loading Logic Source: https://nodejs.org/api/modules.html/index This pseudocode describes the MAYBE_DETECT_AND_LOAD function, which determines whether a given module path should be loaded as a CommonJS module or an ECMAScript module. It relies on parsing and syntax detection. ```pseudocode MAYBE_DETECT_AND_LOAD(X) 1. If X parses as a CommonJS module, load X as a CommonJS module. STOP. 2. Else, if the source code of X can be parsed as ECMAScript module using DETECT_MODULE_SYNTAX defined in the ESM resolver, a. Load X as an ECMAScript module. STOP. 3. THROW the SyntaxError from attempting to parse X as CommonJS in 1. STOP. ``` -------------------------------- ### Importing Modules with require() in Node.js Source: https://nodejs.org/api/modules.html/index The require() function is used to import modules, JSON files, and local files. It can resolve modules from node_modules or use relative paths resolved against __dirname or the current working directory. ```javascript // Importing a local module with a path relative to the `__dirname` or current // working directory. (On Windows, this would resolve to .\path\myLocalModule.) const myLocalModule = require('./path/myLocalModule'); // Importing a JSON file: const jsonData = require('./path/filename.json'); // Importing a module from node_modules or Node.js built-in module: const crypto = require('node:crypto'); ``` -------------------------------- ### Node.js Folder as Module with package.json Source: https://nodejs.org/api/modules.html/index When a folder is passed to require(), Node.js first looks for a package.json file in the folder's root. If found, it attempts to load the module specified by the 'main' field. If 'main' is missing or cannot be resolved, it falls back to index.js or index.node. ```json { "name": "some-library", "main": "./lib/some-library.js" } ``` -------------------------------- ### Node.js Module Exports Shortcut Source: https://nodejs.org/api/modules.html/index Demonstrates the usage of the `exports` shortcut in Node.js modules, which is an alias for `module.exports`. It highlights how assigning directly to `exports` can break the binding with `module.exports` and shows the correct way to reassign `module.exports` when replacing it entirely. ```javascript module.exports.hello = true; // Exported from require of module exports = { hello: false }; // Not exported, only available in the module copy ``` ```javascript module.exports = exports = function Constructor() { // ... etc. }; ``` ```javascript function require(/* ... */) { const module = { exports: {} }; ((module, exports) => { // Module code here. In this example, define a function. function someFunc() {} exports = someFunc; // At this point, exports is no longer a shortcut to module.exports, and // this module will still export an empty default object. module.exports = someFunc; // At this point, the module will now export someFunc, instead of the // default object. })(module, module.exports); return module.exports; } ``` -------------------------------- ### require.resolve.paths Source: https://nodejs.org/api/modules.html/index The require.resolve.paths function returns an array of paths that would be searched during module resolution. ```APIDOC ## require.resolve.paths(request) ### Description Returns an array containing the paths searched during resolution of `request` or `null` if the `request` string references a core module. ### Added in v8.9.0 ### Parameters * `request` (string) - The module path whose lookup paths are being retrieved. ### Returns * `` | `` - An array of paths or null. ### Example ```javascript const paths = require.resolve.paths('express'); console.log(paths); ``` ``` -------------------------------- ### Node.js Module Require Functionality Source: https://nodejs.org/api/modules.html/index Illustrates how to use `module.require(id)` in Node.js to load a module as if `require()` was called from the original module. This requires obtaining a reference to the `module` object itself. ```javascript // Example usage would require exporting the module object itself // For instance, within a module: // exports.require = module.require.bind(module); // Then in another module: // const currentModule = require('./this_module'); // const loadedModule = currentModule.require('./another_module'); ``` -------------------------------- ### Node.js ESM Match Resolution Source: https://nodejs.org/api/modules.html/index This pseudocode defines the RESOLVE_ESM_MATCH function, which takes a resolved module path (potentially from an ESM context) and attempts to load it. It checks for file existence and throws an error if not found. ```pseudocode RESOLVE_ESM_MATCH(MATCH) 1. let RESOLVED_PATH = fileURLToPath(MATCH) 2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension format. STOP 3. THROW "not found" copy ``` -------------------------------- ### Manipulate Module Cache with require.cache (Node.js) Source: https://nodejs.org/api/modules.html/index Demonstrates how to modify the require.cache object to force module reloading or substitute modules. This method is effective for JavaScript modules but will error for native addons. Use with caution as it can affect built-in module resolution. ```javascript const assert = require('node:assert'); const realFs = require('node:fs'); const fakeFs = {}; require.cache.fs = { exports: fakeFs }; assert.strictEqual(require('fs'), fakeFs); assert.strictEqual(require('node:fs'), realFs); ``` -------------------------------- ### Node.js Folder as Module without package.json Source: https://nodejs.org/api/modules.html/index If a folder is passed to require() and no package.json is present, or the 'main' field is missing, Node.js attempts to load index.js or index.node from that directory. ```javascript require('./some-library'); // Attempts to load './some-library/index.js' or './some-library/index.node' ``` -------------------------------- ### Node.js Node Modules Path Resolution Source: https://nodejs.org/api/modules.html/index This pseudocode defines the NODE_MODULES_PATHS function, which generates a list of directories to search for Node.js modules. It traverses up the directory tree, looking for 'node_modules' folders. ```pseudocode NODE_MODULES_PATHS(START) 1. let PARTS = path split(START) 2. let I = count of PARTS - 1 3. let DIRS = [] 4. while I >= 0, a. if PARTS[I] = "node_modules", GOTO d. b. DIR = path join(PARTS[0 .. I] + "node_modules") c. DIRS = DIRS + DIR d. let I = I - 1 5. return DIRS + GLOBAL_FOLDERS ``` -------------------------------- ### Module Object Source: https://nodejs.org/api/modules.html/index The `module` object is a free variable within each module, providing access to module-specific information and exports. ```APIDOC ## The `module` object ### Description In each module, the `module` free variable is a reference to the object representing the current module. `module.exports` is also accessible via the `exports` module-global. `module` is not actually a global but rather local to each module. ### Added in v0.1.16 ### Type `` #### `module.children` * **Description**: The module objects required for the first time by this one. * **Type**: `` #### `module.exports` * **Description**: The `module.exports` object is created by the `Module` system. It is used to define what a module exports. Assigning to `module.exports` must be done immediately and cannot be done in callbacks. * **Type**: `` ### Example ```javascript // a.js const EventEmitter = require('node:events'); module.exports = new EventEmitter(); // Do some work, and after some time emit // the 'ready' event from the module itself. setTimeout(() => { module.exports.emit('ready'); }, 1000); // b.js const a = require('./a'); a.on('ready', () => { console.log('module "a" is ready'); }); ``` ### Warning Assignment to `module.exports` must be done immediately. It cannot be done in any callbacks. The following will not work: ```javascript // x.js setTimeout(() => { module.exports = { a: 'hello' }; }, 0); // y.js const x = require('./x'); console.log(x.a); // This will likely log undefined ``` ``` -------------------------------- ### Node.js Self Package Exports Resolution Source: https://nodejs.org/api/modules.html/index This pseudocode describes the LOAD_PACKAGE_SELF function, which resolves module specifiers within the same package based on the 'exports' field in package.json. It's used for internal package imports. ```pseudocode LOAD_PACKAGE_SELF(X, DIR) 1. Find the closest package scope SCOPE to DIR. 2. If no scope was found, return. 3. If the SCOPE/package.json "exports" is null or undefined, return. 4. If the SCOPE/package.json "name" is not the first segment of X, return. 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE), "." + X.slice("name".length), `package.json` "exports", ["node", "require"]) defined in the ESM resolver. 6. RESOLVE_ESM_MATCH(MATCH) ``` -------------------------------- ### Node.js File Extension Resolution Source: https://nodejs.org/api/modules.html/index Node.js attempts to load required files with .js, .json, and .node extensions if the exact filename is not found. Files with other extensions must include the extension in the require() call. .json files are parsed, .node files are loaded as compiled addons, and others are parsed as JavaScript. ```javascript require('./file.js'); require('./file.json'); require('./file.node'); require('./file.cjs'); ``` -------------------------------- ### Exporting a Class from a CommonJS Module in Node.js Source: https://nodejs.org/api/modules.html/index Illustrates exporting a class (`Square`) from a Node.js module by assigning it to `module.exports`. This is an alternative to exporting individual properties on `exports` and is necessary when exporting a single entity like a class or function. ```javascript // Assigning to exports will not modify module, must use module.exports module.exports = class Square { constructor(width) { this.width = width; } area() { return this.width ** 2; } }; ``` -------------------------------- ### Node.js Package Import Resolution Source: https://nodejs.org/api/modules.html/index This pseudocode details the LOAD_PACKAGE_IMPORTS function, which resolves module specifiers listed in the 'imports' field of a package.json file. It considers conditions like 'node' and 'require'. ```pseudocode LOAD_PACKAGE_IMPORTS(X, DIR) 1. Find the closest package scope SCOPE to DIR. 2. If no scope was found, return. 3. If the SCOPE/package.json "imports" is null or undefined, return. 4. If `--no-require-module` is not enabled a. let CONDITIONS = ["node", "require", "module-sync"] b. Else, let CONDITIONS = ["node", "require"] 5. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE), CONDITIONS) defined in the ESM resolver. 6. RESOLVE_ESM_MATCH(MATCH). ``` -------------------------------- ### Node.js Package Exports Resolution Source: https://nodejs.org/api/modules.html/index This pseudocode outlines the LOAD_PACKAGE_EXPORTS function, which resolves module specifiers based on the 'exports' field in package.json. It handles subpath imports and applies conditions for resolution. ```pseudocode LOAD_PACKAGE_EXPORTS(X, DIR) 1. Try to interpret X as a combination of NAME and SUBPATH where the name may have a @scope/ prefix and the subpath begins with a slash (`/`). 2. If X does not match this pattern or DIR/NAME/package.json is not a file, return. 3. Parse DIR/NAME/package.json, and look for "exports" field. 4. If "exports" is null or undefined, return. 5. If `--no-require-module` is not enabled a. let CONDITIONS = ["node", "require", "module-sync"] b. Else, let CONDITIONS = ["node", "require"] 6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH, `package.json` "exports", CONDITIONS) defined in the ESM resolver. 7. RESOLVE_ESM_MATCH(MATCH) ``` -------------------------------- ### Customizing require() output with 'module.exports' in ESM Source: https://nodejs.org/api/modules.html/index Shows how an ECMAScript module can export a specific value using the 'module.exports' name to control what is returned by require(). This overrides default namespace object behavior but can lead to loss of named exports. ```javascript // point.mjs export default class Point { constructor(x, y) { this.x = x; this.y = y; } } export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); } export { Point as 'module.exports' } ``` ```javascript const Point = require('./point.mjs'); console.log(Point); // [class Point] // Named exports are lost when 'module.exports' is used const { distance } = require('./point.mjs'); console.log(distance); // undefined ``` -------------------------------- ### Checking if a File is the Main Module in Node.js Source: https://nodejs.org/api/modules.html/index Provides a way to determine if a JavaScript file is being executed directly by Node.js or if it's being loaded as a module by another file. This is achieved by comparing `require.main` with the current `module` object. ```javascript if (require.main === module) { console.log('This file is being run directly'); } else { console.log('This file is being required by another module'); } ``` -------------------------------- ### require.resolve Source: https://nodejs.org/api/modules.html/index The require.resolve function uses the internal require machinery to find the location of a module without loading it. ```APIDOC ## require.resolve(request[, options]) ### Description Use the internal `require()` machinery to look up the location of a module, but rather than loading the module, just return the resolved filename. If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. ### Parameters * `request` (string) - The module path to resolve. * `options` (Object) - Optional. Configuration options for resolution. * `paths` (string[]) - Paths to resolve module location from. If present, these paths are used instead of the default resolution paths. ### Returns * `` - The resolved filename of the module. ### History * v8.9.0: The `paths` option is now supported. * v0.3.0: Added in v0.3.0. ### Example ```javascript const resolvedPath = require.resolve('my-module'); console.log(resolvedPath); ``` ``` -------------------------------- ### Node.js Module Wrapper Function Source: https://nodejs.org/api/modules.html/index Node.js wraps module code in a function to scope top-level variables and provide module-specific global-like variables such as module, exports, __filename, and __dirname. ```javascript (function(exports, require, module, __filename, __dirname) { // Module code actually lives in here }); ``` -------------------------------- ### Node.js Cyclic Module Dependencies Source: https://nodejs.org/api/modules.html/index When modules have circular dependencies (e.g., module A requires module B, and module B requires module A), Node.js returns an unfinished copy of the module's exports to prevent infinite loops. The module then completes loading and its updated exports are provided to the other module. ```javascript // a.js console.log('a starting'); exports.done = false; const b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done'); // b.js console.log('b starting'); exports.done = false; const a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done'); // main.js console.log('main starting'); const a = require('./a.js'); const b = require('./b.js'); console.log('in main, a.done = %j, b.done = %j', a.done, b.done); ``` -------------------------------- ### Node.js Requiring Sub-modules Source: https://nodejs.org/api/modules.html/index It's possible to require specific files or sub-modules within a distributed module by appending a path suffix to the module name. This suffixed path follows the same module resolution semantics. ```javascript require('example-module/path/to/file'); ``` -------------------------------- ### Maintaining named exports with 'module.exports' in ESM Source: https://nodejs.org/api/modules.html/index Illustrates a pattern where the default export of an ESM is an object containing named exports, allowing CommonJS consumers using require() to access both the default export and named exports. ```javascript export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); } export default class Point { constructor(x, y) { this.x = x; this.y = y; } static distance = distance; } export { Point as 'module.exports' } ``` ```javascript const Point = require('./point.mjs'); console.log(Point); // [class Point] const { distance } = require('./point.mjs'); console.log(distance); // [Function: distance] ``` -------------------------------- ### require.cache Source: https://nodejs.org/api/modules.html/index The require.cache object stores loaded modules. Deleting a module from this cache will cause it to be reloaded on the next require call. This does not apply to native addons. ```APIDOC ## require.cache ### Description Modules are cached in this object when they are required. Deleting a key value from this object causes the next `require` to reload the module. This does not apply to native addons. ### Type `` ### Example ```javascript const assert = require('node:assert'); const realFs = require('node:fs'); const fakeFs = {}; require.cache['fs'] = { exports: fakeFs }; assert.strictEqual(require('fs'), fakeFs); assert.strictEqual(require('node:fs'), realFs); ``` ``` -------------------------------- ### Exporting Functions from a CommonJS Module in Node.js Source: https://nodejs.org/api/modules.html/index Shows how to export functions (`area`, `circumference`) from a Node.js module by assigning them to the `exports` object. Variables declared within the module, like `PI`, remain private. ```javascript const { PI } = Math; exports.area = (r) => PI * r ** 2; exports.circumference = (r) => 2 * PI * r; ``` -------------------------------- ### Node.js Module Caching Behavior Source: https://nodejs.org/api/modules.html/index Node.js caches modules after their first load. Subsequent calls to require() for the same module will return the cached object, preventing re-execution. This mechanism is crucial for performance and for handling circular dependencies by returning partially loaded objects. ```javascript const moduleA = require('./moduleA'); const moduleB = require('./moduleA'); // moduleB will be the same object as moduleA ``` -------------------------------- ### Accessing Module File Name (__filename) in Node.js Source: https://nodejs.org/api/modules.html/index The __filename variable provides the absolute path of the current module file, with symlinks resolved. For the main program, this may differ from the command-line argument. ```javascript console.log(__filename); // Prints: /Users/mjr/example.js console.log(__dirname); // Prints: /Users/mjr ``` -------------------------------- ### Accessing Module Directory Name (__dirname) in Node.js Source: https://nodejs.org/api/modules.html/index The __dirname variable provides the absolute path of the directory containing the current module. It is equivalent to path.dirname(__filename). ```javascript const path = require('path'); console.log(__dirname); // Prints: /Users/mjr console.log(path.dirname(__filename)); // Prints: /Users/mjr ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.