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 viamodule.exports.
In other words:
const math = require('./math');means:
"Load the file
math.js, run its code, and return the object it exports."
2. An example
math.js
const PI = 3.14;
function add(a, b) {
return a + b;
}
module.exports = { PI, add };app.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.PI); // 3.14When require('./math') is called:
- Node.js finds the file
math.js; - runs its code;
- reads
module.exports; - returns that object into the
mathvariable.
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:
const math = require('./math');Node.js goes through 5 steps:
1. Path resolution
Node.js looks for the file:
./math.js → ./math.json → ./math.nodeIf the path has no ./, it looks in:
node_modules2. Caching
If the module is already loaded, Node.js returns it from cache (instead of loading it again):
const x = require('./module');
const y = require('./module');
console.log(x === y); // trueThe 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:
(function (exports, require, module, __filename, __dirname) {
// the contents of your file
});This creates an isolated scope and gives access to:
requiremoduleexports__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:
// user.js
module.exports = {
name: 'Tim',
sayHi() {
console.log('Hi!');
}
};Importing:
// 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:
// config.json
{
"port": 3000,
"mode": "production"
}
// app.js
const config = require('./config.json');
console.log(config.port); // 3000For 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.
console.log(require.cache);This speeds things up, but it can be reset:
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:
- Built-in (
fs,path,os,http, ...); - Local (
./math,../utils); - node_modules in the current directory;
- 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:
project/
├── app.js
└── math.jsmath.js
console.log('Loading the math module...');
module.exports = {
add(a, b) { return a + b; },
};app.js
const math = require('./math');
console.log(math.add(2, 3));Running it:
Loading the math module...
5Calling require('./math') again:
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.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.