Skip to main content

What does require() do?

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 typeExampleDescription
Localrequire('./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
JSONrequire('./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

CriterionCommonJS (require)ES Modules (import)
Importrequire()import
Exportmodule.exportsexport
LoadingSynchronousAsynchronous
CachingYesYes
SupportBy default in Node.jsVia "type": "module" or .mjs
Good forNode.js serversModern 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() doesExplanation
Finds the fileResolves the path (.js, .json, .node)
CachesRuns the module once and stores the result
IsolatesWraps the module in an internal function
ExecutesRuns the module's code
ReturnsReturns 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.

Short Answer

Interview ready
Premium

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