agyanadda@gmail.com

Node.js Modules: CommonJS and ES Modules

Node.js Basics 1 min read Updated Dec 3, 2026 Topic 3 of 30

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() {} or export 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

  1. Core modules — built into Node: fs, path, http, events (import as node:fs)
  2. Your own files — paths starting with ./ or ../
  3. 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which line imports a CommonJS module?

Exercise 2 True / False

Adding "type": "module" to package.json enables ES modules for .js files.

Exercise 3 Fill in the Blank

In CommonJS, export values with module.___

Frequently Asked Questions

An ES module can import most CommonJS packages, and newer Node versions can require() many ES modules too, but mixing styles in your own files causes confusion. Pick one style per project, preferably ES modules.