Roadmap › Node.js — Runtime Internals, Express, APIs and SQL Server › Module: Node.js Fundamentals
Lessons in this course (11)
2. Modules — CommonJS vs ES modules, npm and package.json
Basic★ Must knowLesson 2 of 11
js
// CommonJS (default for .js unless "type": "module")
const path = require('node:path');
module.exports = { add: (a, b) => a + b };
// ES modules (.mjs, or "type": "module" in package.json)
import path from 'node:path';
import { readFile } from 'node:fs/promises';
export function add(a, b) { return a + b; }
export default add;| CommonJS | ES modules | |
|---|---|---|
| Syntax | require / module.exports | import / export |
| Loading | Synchronous, at runtime | Static analysis, async loading, top-level await |
__dirname | Available | Use import.meta.dirname (Node 20.11+) |
| Interop | Can require() ESM since Node 22 (sync graphs) | Can import CommonJS |
json
{
"name": "shop-api",
"version": "1.0.0",
"type": "module",
"main": "src/server.js",
"engines": { "node": ">=22" },
"scripts": {
"dev": "node --watch src/server.js",
"start": "node src/server.js",
"test": "node --test",
"lint": "eslint ."
},
"dependencies": { "express": "^5.1.0", "mssql": "^11.0.1", "zod": "^3.24.0" },
"devDependencies": { "eslint": "^9.0.0", "supertest": "^7.0.0" }
}- dependencies ship to production; devDependencies only for development/build.
- Semantic versioning:
^5.1.0allows 5.x.x updates,~5.1.0allows 5.1.x, exact5.1.0pins. - package-lock.json records exact installed versions — commit it; use
npm ciin CI for reproducible installs. npm auditchecks known vulnerabilities;npm outdatedshows updates.