Modules Overview
Node code is organized into reusable files called modules.
Syntax
const fs = require('fs');A module is simply a file of JavaScript whose code can be shared with other files. Splitting a program into modules keeps it organized and reusable.
Three kinds of modules
- Core modules — built into Node, like
fs,http, andpath. No install needed. - Local modules — your own files, loaded by their path (
./utils). - npm modules — third-party packages installed into
node_modules.
You bring a module into your file with require() (CommonJS) or import (ES modules).
Example
// Core module (built in)
const path = require('path');
// Local module (your own file)
const helpers = require('./helpers');
// npm module (installed with npm install)
const express = require('express');
console.log(path.extname('report.pdf')); // .pdfWhen to use it
- A large Express app splits route handlers, middleware, and utilities into separate module files so teams can work in parallel without merge conflicts.
- A shared validation library is published as an npm package and required by both the API server and the admin dashboard via `require()`.
- An internal CLI tool uses `module.exports` to expose a `run()` function that can be both executed directly and imported in tests.
More examples
Export and import a value
Shows the basic CJS module pattern: export an object from one file and require it in another.
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require('./math');
console.log(add(2, 3)); // 5Default export function
Exports a single function as the module's default export and imports it directly.
// greet.js
module.exports = function greet(name) {
return `Hello, ${name}!`;
};
// app.js
const greet = require('./greet');
console.log(greet('Alice'));Require a built-in module
Requires two Node.js built-in modules — no installation needed, just `require` by name.
const os = require('os');
const path = require('path');
console.log('Platform:', os.platform());
console.log('Home dir:', os.homedir());
console.log('Joined:', path.join('/usr', 'local', 'bin'));
Discussion