Skip to main content

What is a module in Node.js?

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

TypeExamplesDescription
Built-in (core modules)fs, path, os, http, events, cryptoShipped with Node.js
User-defined (user modules)./math.js, ./config.jsYour own files and utilities
Third-partyexpress, mongoose, chalkInstalled 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

ModulePurpose
fsFilesystem access
pathWorking with paths
osOS information
http, httpsServers and requests
eventsWorking with events
cryptoEncryption
urlURL parsing
utilDebugging 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

PointCommonJSES Modules
Importrequire()import
Exportmodule.exportsexport
SupportBy defaultVia "type": "module" or .mjs
LoadingSynchronousAsynchronous
Tree-shakingNoYes
Use caseOlder and server projectsModern 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.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.