Node.js Module Systems - CommonJS (CJS) vs ECMAScript Modules (ESM) Architecture

One of the most significant architectural shifts in modern Node.js is the coexistence of two module systems: the legacy CommonJS (CJS) standard created in 2009, and the modern official ECMAScript standard: ES Modules (ESM). Understanding the differences, syntax rules, and interoperability between both systems is essential for every backend developer.

CommonJS vs ES Modules in Node.js Architecture Comparison
Figure 3: Side-by-Side Comparison of CommonJS (CJS) vs ECMAScript Modules (ESM)

1. CommonJS (CJS): The Legacy Default

In CommonJS, modules are loaded synchronously via require() and exported by mutating the module.exports or exports object:

// math-cjs.js (CommonJS Export)
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

module.exports = {
  add,
  multiply
};
// app-cjs.js (CommonJS Import)
const { add, multiply } = require('./math-cjs');

console.log('Sum:', add(10, 20));          // 30
console.log('Product:', multiply(5, 4));    // 20

2. ES Modules (ESM): The Modern Standard

To use ES Modules, set "type": "module" in your package.json. You can then use standardized import and export keywords:

// math-esm.js (ESM Named Exports)
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

// Default export
export default function calculateTax(amount, rate = 0.18) {
  return amount * rate;
}
// app-esm.js (ESM Import)
import calculateTax, { add, multiply } from './math-esm.js';

console.log('Sum:', add(10, 20));                 // 30
console.log('Tax on $100:', calculateTax(100));   // 18
Crucial ESM Rule: Mandatory File Extensions

Unlike CommonJS where you could omit .js when requiring local files, ES Modules in Node.js require explicit file extensions: import { add } from './math.js'. Omission will trigger an ERR_MODULE_NOT_FOUND exception!

Top-Level Await in ES Modules

In CommonJS, you could not use await outside of an async function wrapper. ES Modules fully support Top-Level Await, simplifying database connections and asynchronous setup tasks:

// server-esm.js (Top-Level Await)
import http from 'http';

// Asynchronous setup without wrapping in an IIFE
const res = await fetch('https://api.github.com/zen');
const dailyQuote = await res.text();

console.log('GitHub Zen:', dailyQuote);

CommonJS vs ESM Feature Comparison

Feature CommonJS (CJS) ES Modules (ESM)
Loading Mechanism Synchronous (blocks execution while loading) Asynchronous & Static (parsed before execution)
Conditional Imports Allowed: if (cond) require('./a') Disallowed for static import (Use dynamic import())
Top-Level Await No (Throws SyntaxError) Fully Supported natively
Path Resolution __dirname and __filename globals import.meta.url via node:url module
Tree Shaking Poor (V8 cannot statically predict exports) Optimal (Allows dead-code elimination in bundlers)

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between CommonJS and ES Modules in Node.js?

CommonJS uses synchronous 'require()' and 'module.exports', loading modules at runtime. ES Modules (ESM) use static 'import' and 'export' syntax, loading and parsing module dependencies asynchronously during compile time, enabling static analysis, tree-shaking, and top-level await.

Q2. How do I enable ES Modules in my Node.js project?

You can enable ESM in two ways: 1) Add '"type": "module"' to your root package.json, which treats all .js files as ES Modules; or 2) Give your module files the '.mjs' file extension (e.g. math.mjs).

Q3. Why are __dirname and __filename missing in ES Modules, and what is the replacement?

In ES Modules, Node.js does not wrap code in the CommonJS module wrapper function, so __dirname and __filename are not defined. To obtain the current directory and file path in ESM, use: 'import { fileURLToPath } from "url"; import path from "path"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename);'.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Node.js Globals & Process

Learn how __dirname changes in ESM with import.meta.url.

NPM & package.json Guide

Configure type: module in package.json.

File System Module

Import fs and fs/promises in ESM.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!