Chapter 2 of 12
Modules let you split code across multiple files and import/export what you need. Node.js has two module systems: CommonJS (the original) and ES Modules (the modern standard). You'll see both.
// math.js — export functions
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }
module.exports = { add, multiply }; // export as an object
// or: module.exports.add = add;
// or: exports.add = add; (shorthand)
// app.js — import them
const { add, multiply } = require("./math");
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
// Import a whole module (like built-in 'path')
const path = require("path");
const fs = require("fs");// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14159;
export default function main() { ... }
// app.js
import { add, PI } from "./math.js";
import main from "./math.js"; // default import
import * as mathLib from "./math.js"; // import everything
// To use ES modules in Node.js:
// 1. Add "type": "module" to package.json
// 2. OR rename files to .mjsconst fs = require("fs"); // file system
const path = require("path"); // file paths
const os = require("os"); // operating system info
const http = require("http"); // HTTP server
const https = require("https"); // HTTPS
const url = require("url"); // URL parsing
const crypto = require("crypto"); // cryptography
const events = require("events"); // EventEmitter
const stream = require("stream"); // streams
// These are built in — no npm install needed