A module is a file whose code you can reuse in other files. Node.js supports two module systems.
CommonJS (classic)
- Export:
module.exports = { add, multiply }; - Import:
const { add } = require('./math');
ES Modules (modern)
- Export:
export function add() {}orexport default ... - Import:
import { add } from './math.js';
To use ES modules, either name files .mjs or add "type": "module" to package.json. With ES modules you must write the file extension (./math.js).
Three kinds of modules
- Core modules — built into Node:
fs,path,http,events(import asnode:fs) - Your own files — paths starting with
./or../ - npm packages — installed in
node_modules, e.g.express
New projects should prefer ES modules; you will still see require in many tutorials and older code.
Example
Example — The same module in both styles
JavaScript
// ---- CommonJS ----
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require('./math');
console.log(add(2, 3)); // 5
// ---- ES Modules (package.json has "type": "module") ----
// math.js
export function add(a, b) { return a + b; }
export default function square(n) { return n * n; }
// app.js
import square, { add } from './math.js';
import { readFile } from 'node:fs/promises';
console.log(add(2, 3), square(4)); // 5 16
Both print the same result. ES modules use import/export and need the .js extension in the path.