CommonJS & ES Modules

🌿 Node.js Lesson 2 Beginner

Node.js supports two module systems: the original CommonJS (CJS) format using require(), and the modern ES Modules (ESM) format using import/export. Understanding both is essential for working with real-world Node projects.

1 CommonJS Modules

CommonJS is the default module system in Node.js. Every file is its own module with its own scope:

JavaScript — math.js (CommonJS)
// Exporting from a module
const PI = 3.14159;

function circleArea(r) {
  return PI * r * r;
}

function circumference(r) {
  return 2 * PI * r;
}

// Export as an object
module.exports = { circleArea, circumference, PI };
JavaScript — main.js (requiring)
const { circleArea, PI } = require('./math');

console.log('Area:', circleArea(5));    // Area: 78.53975
console.log('PI value:', PI);          // PI value: 3.14159

// Require built-in modules (no path needed)
const os = require('os');
console.log('CPU cores:', os.cpus().length);
2 ES Modules (ESM)

To use ESM in Node.js, either name files .mjs or add "type": "module" to your package.json:

JavaScript — ES Module syntax
// utils.mjs — named exports
export const VERSION = '1.0.0';

export function greet(name) {
  return 'Hello, ' + name + '!';
}

export default function main() {
  console.log('Default export function');
}
JavaScript — Importing ESM
// Import named + default exports
import main, { greet, VERSION } from './utils.mjs';

console.log(VERSION);       // 1.0.0
console.log(greet('Node')); // Hello, Node!
main();                     // Default export function

// Dynamic import (works in both CJS and ESM contexts)
const { circleArea } = await import('./math.mjs');
3 Code Challenge
Challenge: Create a validator.js module that exports two functions: isEmail(str) and isPhone(str) using regex validation. Import and test them from a separate test.js file.