These are the notes for JavaScript episode 18. A program that lives in one big file puts every name in one shared space, so names clash: one function silently replaces another, or a duplicate const stops the program before it starts. You'll invent the fix, modules: one file per job, each with its own scope, sharing only what it exports. You'll use Node's built-in modules, write CommonJS modules with module.exports and require, see the module cache, and then write ES modules with export, export default and import, and learn how Node decides which system a file uses. Every output and error below is real Node.js 24 output. The SyntaxPilot compiler runs one file (main.js); the two-file examples are for your own computer (any folder, node main.js).
Builds on: functions (episode 9), scope (10), destructuring (12), classes (16).
The real-life idea: the one-drawer kitchen
A big joint family keeps everything in one kitchen drawer. One day two people each put in a box labelled "salt"; one is actually sugar. Someone grabs the wrong one and the dal is ruined. Nobody did anything wrong on their own: the single drawer is the problem. Every kitchen ends up with separate dabbas, each holding its own things, with a label saying what's inside.
| Kitchen | JavaScript |
|---|---|
| One giant drawer | one big file: every top-level name in one scope |
| Two boxes with the same label | two functions or variables with the same name |
| Separate dabbas | modules: one file per job, each with its own scope |
| The label on a dabba | exports: what a module shares |
| Taking two spoons of jeera | require / import: take exactly what you need |
The problem: one big file
A function silently replaced
// ---- Asha's part: the bill ----
function format(amount) {
return `₹${amount.toFixed(2)}`;
}
// ---- Ravi's part, 400 lines later: the report ----
function format(name) {
return name.toUpperCase();
}
// ---- the bill ----
console.log("Total:", format(45));
/tmp/.../main.js:7
return name.toUpperCase();
^
TypeError: name.toUpperCase is not a function
The bill called Ravi's format. The second function declaration with the same name replaced the first one everywhere in the file, even above it (function declarations are hoisted, episode 10). No warning about the clash itself.
A duplicate const
const total = 45;
console.log("Bill total:", total);
// ... 300 lines later, someone else ...
const total = 3;
console.log("Report total:", total);
/tmp/.../main.js:4
const total = 3;
^
SyntaxError: Identifier 'total' has already been declared
Caught, but not even line 1 ran.
Why it failed: all top-level names in a file live in one shared scope. With hundreds of lines and several people, every name must be unique across the whole file. That doesn't scale.
The fix: modules
- A module is a file with its own scope: names declared in it are private to it.
- A module exports what it wants to share.
- Another file imports (or requires) what it needs.
cart.js (add, itemCount) report.js (format)
\ /
└──────► main.js ◄────┘ uses both
Asha's format and Ravi's format can now live in different files without ever clashing.
Built-in modules
Node ships with ready-made modules for common jobs. Load them with require. The node: prefix says "this is a built-in, not one of my files".
const path = require("node:path");
const os = require("node:os");
console.log(path.join("menu", "drinks", "chai.txt"));
console.log(path.extname("bill.pdf"));
console.log(typeof os.cpus().length);
console.log(typeof require, typeof module, typeof module.exports);
menu/drinks/chai.txt
.pdf
number
function object object
path.joinjoins folder names with the right separator for the system (/on Linux and macOS,\on Windows).path.extnamegives the extension.os.cpus()lists the CPU cores.- Every CommonJS file automatically gets
require(a function),module(an object describing this file) andmodule.exports(the object this file shares, empty to start with).
Other built-ins you'll use: node:fs (files), node:readline (line-by-line input), node:http (web servers), node:test (tests, episode 30).
CommonJS: module.exports and require
Cannot find module
const cart = require("./cart");
console.log(cart);
node:internal/modules/cjs/loader:1568
throw err;
^
Error: Cannot find module './cart'
Require stack:
- /tmp/.../main.js
./ means "a file in the same folder as this one". There is no cart.js yet.
Proving a module is just a file
In the compiler, main.js can write cart.js into its own folder with fs.writeFileSync, then require it. (On your computer you'd simply create cart.js in your editor.)
const fs = require("node:fs");
fs.writeFileSync("cart.js", `
let count = 0;
function add(item, price) {
count++;
return \`\${item}: ₹\${price}\`;
}
function itemCount() {
return count;
}
module.exports = { add, itemCount };
console.log("cart.js loaded");
`);
const cart = require("./cart");
console.log(cart.add("Chai", 20));
console.log(cart.add("Samosa", 15));
console.log(cart.itemCount(), cart.count);
const again = require("./cart");
console.log(again === cart);
console.log(fs.readdirSync("."));
cart.js loaded
Chai: ₹20
Samosa: ₹15
2 undefined
true
[ 'cart.js', 'main.js' ]
module.exports = { add, itemCount }is whatcart.jsshares.require("./cart")returns exactly that object (the.jsextension is optional in CommonJS).cart.countisundefined:countwas not exported, so it stays private. OnlyaddanditemCountcan change or read it."cart.js loaded"printed once, andagain === cartistrue: Node runs a module the first time it's required and remembers its exports. This is the module cache. Every file that requires./cartshares the same object (and the samecount).- The
\`` and\${` inside the template literal are escapes, because the file's text is itself written inside a template literal.
Forgetting to export
const fs = require("node:fs");
fs.writeFileSync("cart.js", `
function add(item, price) {
return \`\${item}: ₹\${price}\`;
}
`);
const cart = require("./cart");
console.log(cart);
console.log(cart.add("Chai", 20));
{}
/tmp/.../main.js:9
console.log(cart.add("Chai", 20));
^
TypeError: cart.add is not a function
Nothing is shared unless you export it.
The two-file version (on your computer)
cart.js
let count = 0; // private to this file
function add(item, price) {
count++;
return `${item}: ₹${price}`;
}
function itemCount() {
return count;
}
module.exports = { add, itemCount };
main.js
const { add, itemCount } = require("./cart");
console.log(add("Chai", 20));
console.log(add("Samosa", 15));
console.log(itemCount());
$ node main.js
Chai: ₹20
Samosa: ₹15
2
main.js destructures (episode 12) exactly the names it needs. This system (require + module.exports) is called CommonJS. It's what Node has used since 2009, and you'll find it in many existing projects.
Trap:
exports.add = addworks (it adds tomodule.exports), butexports = { add }does not: it only reassigns a local variable, and the module still exports{}. Prefermodule.exports = { ... }.
To export a single thing, such as a class, assign it directly: module.exports = Question; and then const Question = require("./question");.
ES modules: export and import
In 2015, JavaScript itself got a module system, built into the language and supported by browsers and Node: ES modules (ESM).
- Put
exportin front of what you share: named exports. - A file can also have one main export:
export default. import { a, b } from "./file.mjs"takes named exports (names must match);import anything from "./file.mjs"takes the default export (you pick the name);asrenames.
cart.mjs
let count = 0;
export function add(item, price) {
count++;
return `${item}: ₹${price}`;
}
export function itemCount() {
return count;
}
export default function receipt(shop) {
return `--- ${shop} ---`;
}
main.mjs
import receipt, { add, itemCount } from "./cart.mjs";
import { add as addItem } from "./cart.mjs";
console.log(receipt("Ramesh's stall"));
console.log(add("Chai", 20));
console.log(addItem("Samosa", 15));
console.log(itemCount());
$ node main.mjs
--- Ramesh's stall ---
Chai: ₹20
Samosa: ₹15
2
- In ES modules, the file extension is required:
"./cart.mjs", not"./cart". import * as cart from "./cart.mjs"gives one object with every export:Object.keys(cart)is[ 'add', 'default', 'itemCount' ].- ES modules are always in strict mode, and imports are loaded before any code in the file runs.
How Node decides which system a file uses
| File | System |
|---|---|
name.cjs |
always CommonJS |
name.mjs |
always ES module |
name.js with "type": "module" in the nearest package.json |
ES module |
name.js with "type": "commonjs" (or no type) |
CommonJS |
name.js with no package.json setting, using import/export |
Node 22+ detects it and runs it as an ES module |
package.json is a small file at the root of a project that describes it (name, version, dependencies, settings). For example:
{
"name": "chai-shop",
"type": "module"
}
One file, one system
import { join } from "node:path";
console.log(join("menu", "chai.txt"));
console.log(typeof require);
menu/chai.txt
undefined
Node saw import and ran main.js as an ES module, which has no require. Mixing them:
import { join } from "node:path";
const fs = require("node:fs");
console.log(join("menu", "chai.txt"));
file:///tmp/.../main.js:2
const fs = require("node:fs");
^
ReferenceError: require is not defined in ES module scope, you can use import instead
Use import fs from "node:fs"; (or import { readFileSync } from "node:fs";).
Two more ES module errors
import { add } from "./cart"; // in main.mjs, no extension
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/.../cart' imported from /.../main.mjs
import { total } from "./cart.mjs"; // cart.mjs exports no "total"
SyntaxError: The requested module './cart.mjs' does not provide an export named 'total'
CommonJS vs ES modules
| CommonJS | ES modules | |
|---|---|---|
| Share | module.exports = { add } |
export function add / export default |
| Use | const { add } = require("./cart") |
import { add } from "./cart.js" |
| Extension in the path | optional | required |
| Files | .cjs, or .js by default |
.mjs, or .js with "type": "module" |
| Runs in | Node | Node and browsers |
| Strict mode | only with "use strict" |
always |
| Since | 2009 (Node) | 2015 (the language standard) |
| Use it for | reading and maintaining existing code | new code |
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
two function format in one file |
(no error) the second replaces the first; here TypeError: name.toUpperCase is not a function |
one shared scope | separate modules |
two const total in one file |
SyntaxError: Identifier 'total' has already been declared |
one shared scope | separate modules or different names |
require("./cart") with no such file |
Error: Cannot find module './cart' |
wrong file name or folder | check the path; own files start with ./ |
require("cart") for your own file |
Error: Cannot find module 'cart' |
without ./ Node looks for a built-in or installed package |
require("./cart") |
no module.exports in cart.js |
{} then TypeError: cart.add is not a function |
nothing exported | module.exports = { add } |
exports = { add } |
{} |
reassigns a local variable only | module.exports = { add } |
require(...) in an ES module |
ReferenceError: require is not defined in ES module scope, you can use import instead |
mixing systems | import ... from |
import { add } from "./cart" |
Error [ERR_MODULE_NOT_FOUND]: Cannot find module ... |
ESM needs the extension | "./cart.mjs" |
import { total } from "./cart.mjs" |
SyntaxError: The requested module './cart.mjs' does not provide an export named 'total' |
no such named export | export it, or fix the name |
Mini project: split the quiz game
quiz/
├── questions.mjs export default [ { q, options, answer }, ... ]
├── engine.mjs export function score(questions, answers)
└── main.mjs import questions from "./questions.mjs"; import { score } from "./engine.mjs";
questions.mjs
export default [
{ q: "Capital of India?", answer: "B" },
{ q: "2 + 2 * 2 = ?", answer: "A" },
{ q: "Chai is made from?", answer: "C" },
];
engine.mjs
export function score(questions, answers) {
return questions.filter((question, i) => (answers[i] || "").trim().toUpperCase() === question.answer).length;
}
main.mjs
import questions from "./questions.mjs";
import { score } from "./engine.mjs";
const answers = ["b", "A", "x"];
console.log(`Score: ${score(questions, answers)}/${questions.length}`);
$ node main.mjs
Score: 2/3
Each file has one job; adding questions never touches the engine.
Practice
- Do the mini project again with CommonJS (
.jsfiles,module.exports,require). - Export the
Questionclass from episode 16 fromquestion.mjsas the default export, and use it inmain.mjs. - Use
node:pathto print the file name without its folder and the extension of"notes/js/ep18.md".
Solutions
-
questions.js:
module.exports = [ ... ];· engine.js:function score(...) { ... } module.exports = { score };· main.js:const questions = require("./questions"); const { score } = require("./engine");. The output is the same:Score: 2/3. -
question.mjs
export default class Question {
constructor(text, answer) { this.text = text; this.answer = answer; }
check(given) { return given.trim().toUpperCase() === this.answer; }
}
main.mjs
import Question from "./question.mjs";
const q = new Question("Capital of India?", "B");
console.log(q.check(" b"));
true
3.
const path = require("node:path");
console.log(path.basename("notes/js/ep18.md"), path.extname("notes/js/ep18.md"));
ep18.md .md
Quick quiz
counter.js and main.js are in the same folder. What does node main.js print?
// counter.js
let n = 0;
module.exports = { inc() { return ++n; } };
// main.js
const a = require("./counter");
const b = require("./counter");
console.log(a.inc(), b.inc(), a.n);
- A.
1 2 undefined - B.
1 1 undefined - C.
1 2 2 - D.
Error: Cannot find module
Answer
A. The module cache gives a and b the very same object, so they share one n: 1, then 2. n was never exported, so a.n is undefined.
Interview questions
- What is a module? Why split code into modules?
- What is module scope? Why can't two modules' variables clash?
- What is the difference between CommonJS and ES modules?
- What's the difference between
module.exportsandexports? - What is the module cache? What happens if two files require the same module?
- Named vs default exports: when would you use each?
- How does Node decide whether a
.jsfile is CommonJS or an ES module? - Why does
requirefail inside an ES module? - Why must you write the extension in ES module imports?
- What does the
node:prefix mean?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Module | a file with its own scope that shares chosen values | cart.js |
| Scope | the region of code where a name is visible | a module's top-level names are visible only in that file |
| Global / shared scope | one space of names for a whole file or program | the one-drawer kitchen |
| Name clash | two things with the same name in the same scope | two function format |
| Export | what a module shares | module.exports = { add }, export function add |
| Import / require | taking what another module exports | require("./cart"), import { add } from "./cart.mjs" |
| Built-in module | a module that ships with Node | node:path, node:fs, node:os |
node: prefix |
marks a built-in module | require("node:fs") |
| Relative path | a path starting from the current file's folder | ./cart, ../utils/money |
| CommonJS (CJS) | Node's original module system | require + module.exports |
module.exports |
the object a CommonJS file shares | module.exports = { add, itemCount } |
require(path) |
loads a CommonJS module and returns its exports | const cart = require("./cart") |
| Module cache | Node runs each module once and reuses its exports | require("./cart") === require("./cart") |
| ES modules (ESM) | the module system built into the JavaScript language | export + import |
| Named export | an export with a fixed name | export function add → import { add } |
| Default export | a module's one main export; the importer picks the name | export default receipt → import receipt |
as |
renames an import | import { add as addItem } |
import * as |
imports every export as one object | import * as cart from "./cart.mjs" |
.mjs / .cjs |
extensions that force ESM / CommonJS | main.mjs |
package.json |
a project's description file; "type" picks the module system |
{ "type": "module" } |
ERR_MODULE_NOT_FOUND |
ESM couldn't find the imported file | missing .mjs extension |
Summary
- One big file means one shared scope: names clash, silently or with a SyntaxError.
- A module is a file with its own scope; it shares only what it exports, and its other names stay private.
- Node has built-in modules (
node:path,node:fs,node:os). - CommonJS:
module.exports = { ... }andrequire("./file"). Each module runs once and is cached. - ES modules:
export,export default,import { } from "./file.mjs"(extension required),asto rename. .cjs/.mjs/"type": "module"decide the system; one system per file. Read CommonJS; write new code as ES modules.
Next episode: JSON. Objects vanish when a program ends and files only hold text, so how do you turn an object into text and back?