Node.js
backendnodejsGuideBeginner
Node.js Modules: ESM & CommonJS
Master ECMAScript Modules (ESM) and CommonJS (CJS) in Node.js, native module prefixes, top-level await, and interop rules.
Verified: 2026-09-30
Tested on:node 22.x
Platforms:
node
#nodejs#modules#esm#commonjs#imports
Overview
Node.js supports two module systems:
- ECMAScript Modules (ESM): Modern official JavaScript standard (
import/export). - CommonJS (CJS): Legacy Node.js standard (
require()/module.exports).
ECMAScript Modules (ESM) (Recommended)
Enable ESM by adding "type": "module" in your package.json or by using the .mjs file extension.
Exporting and Importing
// math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
export default function multiply(a, b) {
return a * b;
}// app.js
import multiply, { add, PI } from './math.js';
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20Top-Level await
In ESM, you can use await directly at the top level of a module without wrapping it in an async function:
// db.js
import { connectDB } from './database.js';
// Automatically pauses module initialization until connected
export const db = await connectDB(process.env.DATABASE_URL);Native Node.js Built-in Prefix (node:)
Always prefix built-in core modules with node: to avoid collisions with third-party packages:
import fs from 'node:fs/promises';
import path from 'node:path';
import http from 'node:http';
import { fileURLToPath } from 'node:url';CommonJS (CJS) (Legacy)
CommonJS is the legacy module format enabled by default when "type": "module" is absent, or when using .cjs files:
// utils.cjs
function formatName(name) {
return name.trim().toUpperCase();
}
module.exports = {
formatName,
};// index.cjs
const { formatName } = require('./utils.cjs');
console.log(formatName(' Alice '));Summary: ESM vs CommonJS
| Feature | ESM (import) | CommonJS (require) |
|---|---|---|
| Loading Mechanism | Asynchronous / Static analysis | Synchronous / Dynamic runtime |
| Top-Level Await | Native support | Not supported |
| Tree-Shaking | Optimized by bundlers | Difficult to optimize |
| File Extension | Required in native ESM imports (./file.js) | Optional in CJS (./file) |
| Directory Scope | import.meta.url | __dirname, __filename |