Suggest an editImprove this articleRefine the answer for “What does require() do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)`require()` is Node.js's built-in function that loads and runs a module, then returns whatever that module exported via `module.exports`; the result is cached, so calling the same path again doesn't re-read the file. **Key point:** Node.js searches for a module in this order - built-in → local → `node_modules`, walking up the directory tree.Shown above the full answer for quick recall.Answer (EN)Image## 1. What `require()` does > `require()` is Node.js's built-in function that **loads and runs a module**, then returns whatever the module exports via `module.exports`. In other words: ```javascript const math = require('./math'); ``` means: > "Load the file `math.js`, run its code, and return the object it exports." ## 2. An example ### math.js ```javascript const PI = 3.14; function add(a, b) { return a + b; } module.exports = { PI, add }; ``` ### app.js ```javascript const math = require('./math'); console.log(math.add(2, 3)); // 5 console.log(math.PI); // 3.14 ``` When `require('./math')` is called: 1. Node.js finds the file `math.js`; 2. runs its code; 3. reads `module.exports`; 4. returns that object into the `math` variable. ## 3. What can be "required" | Module type | Example | Description | |---|---|---| | **Local** | `require('./utils')` | A file in your project (`.js`, `.json`, `.node`) | | **Built-in (core)** | `require('fs')`, `require('path')` | Modules built into Node.js | | **Third-party (npm)** | `require('express')` | Modules from `node_modules` | | **JSON** | `require('./data.json')` | Node.js automatically parses JSON | | **Compiled C++** | `require('./addon.node')` | Native modules | ## 4. What happens under the hood When you call: ```javascript const math = require('./math'); ``` Node.js goes through 5 steps: ### 1. Path resolution Node.js looks for the file: ```javascript ./math.js → ./math.json → ./math.node ``` If the path has no `./`, it looks in: ```javascript node_modules ``` ### 2. Caching If the module is already loaded, Node.js **returns it from cache** (instead of loading it again): ```javascript const x = require('./module'); const y = require('./module'); console.log(x === y); // true ``` The cache lives in `require.cache`. ### 3. Loading Node.js reads the file's contents (if it wasn't found in the cache). ### 4. Wrapping Node.js wraps the module's code in an internal function: ```javascript (function (exports, require, module, __filename, __dirname) { // the contents of your file }); ``` This creates an isolated scope and gives access to: - `require` - `module` - `exports` - `__filename` - `__dirname` ### 5. Execution The module's code runs, and whatever gets assigned to `module.exports` becomes the result of `require()`. ## 5. Export and import together ### Exporting: ```javascript // user.js module.exports = { name: 'Tim', sayHi() { console.log('Hi!'); } }; ``` ### Importing: ```javascript // app.js const user = require('./user'); console.log(user.name); // 'Tim' user.sayHi(); // 'Hi!' ``` ## 6. Support for JSON and other types Node.js can automatically parse JSON: ```javascript // config.json { "port": 3000, "mode": "production" } // app.js const config = require('./config.json'); console.log(config.port); // 3000 ``` For native binary modules (`.node`), Node loads the compiled C++ code. ## 7. The caching mechanism Every module runs **only once**. The result is stored in `require.cache`. ```javascript console.log(require.cache); ``` This speeds things up, but it can be reset: ```javascript delete require.cache[require.resolve('./math')]; ``` ## 8. The module search order When you call `require('name')`, Node.js searches for the module in this order: 1. **Built-in** (`fs`, `path`, `os`, `http`, ...); 2. **Local** (`./math`, `../utils`); 3. **node_modules** in the current directory; 4. then further up the directory tree, until it reaches the root. ## 9. The difference from ES Modules | Criterion | CommonJS (`require`) | ES Modules (`import`) | |---|---|---| | Import | `require()` | `import` | | Export | `module.exports` | `export` | | Loading | Synchronous | Asynchronous | | Caching | Yes | Yes | | Support | By default in Node.js | Via `"type": "module"` or `.mjs` | | Good for | Node.js servers | Modern frontend and Node.js 13+ | ## 10. A full-cycle example ### Files: ```javascript project/ ├── app.js └── math.js ``` ### math.js ```javascript console.log('Loading the math module...'); module.exports = { add(a, b) { return a + b; }, }; ``` ### app.js ```javascript const math = require('./math'); console.log(math.add(2, 3)); ``` ### Running it: ```javascript Loading the math module... 5 ``` Calling `require('./math')` again: ```javascript 5 ``` (the line "Loading the math module..." doesn't print again, the module is cached) ## Quick summary | What `require()` does | Explanation | |---|---| | Finds the file | Resolves the path (`.js`, `.json`, `.node`) | | Caches | Runs the module once and stores the result | | Isolates | Wraps the module in an internal function | | Executes | Runs the module's code | | Returns | Returns the `module.exports` object | ## In one sentence > `require()` is Node.js's built-in function that loads, runs, and returns a module's export (`module.exports`), providing modularity and code isolation in the CommonJS system.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.