Suggest an editImprove this articleRefine the answer for “What is a module in Node.js?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)In Node.js, every file is its own module with an isolated scope; it can export code via `module.exports` (CommonJS) or `export` (ES Modules) and import code from other modules. **Key point:** modules come in three kinds - built-in (`fs`, `http`), user-defined (your own files), and third-party (from npm) - and Node.js looks for them in exactly that order.Shown above the full answer for quick recall.Answer (EN)Image## 1. What a module is In Node.js, **every file is a separate module.** When you create a file `math.js`, Node.js automatically wraps it in an internal function: ```javascript (function (exports, require, module, __filename, __dirname) { // your code }); ``` Thanks to this: - every file has **its own scope** (no global variables); - you can **export** just what's needed; - you can **import** code from other modules. ## 2. Types of modules in Node.js | Type | Examples | Description | |---|---|---| | **Built-in (core modules)** | `fs`, `path`, `os`, `http`, `events`, `crypto` | Shipped with Node.js | | **User-defined (user modules)** | `./math.js`, `./config.js` | Your own files and utilities | | **Third-party** | `express`, `mongoose`, `chalk` | Installed via npm | ## 3. CommonJS modules (the default) ### 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 ``` Here: - `module.exports` → the object `require()` returns; - `require()` → the function that imports a module. ## 4. ES Modules (the modern standard) If `package.json` has `"type": "module"`, you can use ES6 syntax: ### math.js ```javascript export const PI = 3.14; export function add(a, b) { return a + b; } ``` ### app.js ```javascript import { add, PI } from './math.js'; console.log(add(2, 3)); // 5 console.log(PI); // 3.14 ``` Supported natively since Node.js v13+, but it requires `"type": "module"` or the `.mjs` extension. ## 5. How Node.js loads a module When you call `require('./math')`, Node.js goes through 5 steps: 1. **Path resolution** Figures out where the file is (`.js`, `.json`, `.node`). 2. **Caching** If the module is already loaded, it's returned from the cache. 3. **Loading** Node.js reads the file's content from disk. 4. **Wrapping** The module's code is wrapped in an internal function. 5. **Execution** Node.js runs the code and returns `module.exports`. ## 6. An example of the internal wrapper Under the hood, Node.js does roughly this: ```javascript (function (exports, require, module, __filename, __dirname) { const PI = 3.14; module.exports = { PI }; }); ``` Thanks to this: - the module is isolated; - you get access to paths (`__dirname`, `__filename`); - code can be exported via `module.exports`. ## 7. Node.js's built-in (core) modules | Module | Purpose | |---|---| | `fs` | Filesystem access | | `path` | Working with paths | | `os` | OS information | | `http`, `https` | Servers and requests | | `events` | Working with events | | `crypto` | Encryption | | `url` | URL parsing | | `util` | Debugging utilities | Example: ```javascript const os = require('os'); console.log(os.platform()); // 'win32' or 'linux' ``` ## 8. Third-party modules (npm) Installed via npm: ```javascript npm install chalk ``` Usage: ```javascript import chalk from 'chalk'; console.log(chalk.green('Success!')); ``` They live in the `node_modules` folder and are listed in `package.json`. ## 9. Module caching Node.js loads a module **once**, then reads it from cache afterward: ```javascript require('./math'); require('./math'); // the second call doesn't re-read the file ``` This speeds things up, but if a module needs re-initializing, the cache can be cleared: ```javascript delete require.cache[require.resolve('./math')]; ``` ## 10. Path and scope A module can be: - **local** (`./math.js`); - **global** (a built-in like `fs`); - **installed via npm** (`express`). Node.js looks for them in this order: 1. Built-in (`fs`, `path`); 2. Local (`./` or `../`); 3. In `node_modules` (walking up from the current folder). ## 11. An example project layout ```javascript project/ ├── package.json ├── app.js ├── config/ │ └── db.js ├── utils/ │ └── logger.js └── routes/ └── userRoutes.js ``` In `app.js`: ```javascript const db = require('./config/db'); const logger = require('./utils/logger'); const routes = require('./routes/userRoutes'); ``` Every file is a module. Every module exports its own functions and doesn't interfere with the rest. ## 12. Quick summary | Point | CommonJS | ES Modules | |---|---|---| | **Import** | `require()` | `import` | | **Export** | `module.exports` | `export` | | **Support** | By default | Via `"type": "module"` or `.mjs` | | **Loading** | Synchronous | Asynchronous | | **Tree-shaking** | No | Yes | | **Use case** | Older and server projects | Modern modules and frontend | ## In one sentence > A **module in Node.js** is an independent file of code (JS, JSON, or a native binary) that exports specific data or functions and can be imported into other files via `require()` or `import`.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.