Course outline · 0% complete

0/29 lessons0%

Course overview →

Modules: Splitting Code into Files

lesson 2-1 · ~9 min · 4/29

Quiz

Warm-up from lesson 1-2. You wrote loadConfig(callback), which used setTimeout before calling the callback. The code after the loadConfig(...) call printed first. Why?

Why modules exist

A real backend is thousands of lines. Nobody sane keeps that in one file. Node lets you split code into modules: files that export some values and import what they need from others.

The classic Node style is called CommonJS. A file exports by assigning to module.exports, and imports with require:

// mathUtils.js
function add(a, b) {
  return a + b;
}

module.exports = { add };
// app.js
const mathUtils = require("./mathUtils");

console.log(mathUtils.add(2, 3)); // 5

The ./ means "a file next to me". Without it, require("fs") reaches for a built-in module, or one installed with npm, Node's package manager: a command-line tool plus a public registry of shared code, which you will use to install Express in unit 5.

The newer syntax: ES modules

Modern JavaScript added its own module syntax, ESM, which Node also supports (in .mjs files or with "type": "module" in package.json):

// mathUtils.mjs
export function add(a, b) {
  return a + b;
}
// app.mjs
import { add } from "./mathUtils.mjs";
console.log(add(2, 3));
CommonJSESM
exportmodule.exports = {...}export
importrequire(...)import ... from
where you meet itmost Node tutorials and older codenew projects, frontend code

Either way, the shape is the same: a module is an object of things it chose to share. The exercises here run in one file, so you will practice that shape directly.

Code exercise · javascript

Run this. The mathUtils object plays the role of module.exports: a bundle of related functions with everything else kept private.

Code exercise · javascript

Your turn. Build a format "module": an object with one function money(cents) that turns 1234 into the string "$12.34". Divide by 100 and use .toFixed(2) to always keep two decimals.