Synchronous Loading in CommonJS
What you'll learn: How require() blocks code execution until a module finishes loading.
The Blocking Nature of require()
In CommonJS, when you call require(), JavaScript stops everything and waits for the module to load completely before continuing. This is called synchronous or blocking execution.
Think of it like ordering food at a counter where there's only one cashier. You place your order and stand there waiting. Nobody behind you can order until you get your food and move away. That's how require() works—it blocks the line.
How It Works in Practice
console.log('Before require');
const utils = require('./utils'); // Execution pauses here
console.log('After require');
JavaScript will:
- Print "Before require"
- Stop and wait while it reads, parses, and executes
utils.js - Only then print "After require"
If utils.js takes time to load or has complex initialization code, your program simply waits. There's no continuing forward, no parallelism—just patient waiting.
Why This Matters
This synchronous behavior is why CommonJS works well in Node.js (where files load quickly from disk) but wasn't originally suitable for browsers (where network requests are slow). It's also why multiple require() calls in sequence can add up:
const moduleA = require('./a'); // waits
const moduleB = require('./b'); // waits again
const moduleC = require('./c'); // waits again
Each one blocks until complete.
Key Takeaway: require() is synchronous—it halts your program's execution until the requested module is fully loaded and ready, making module loading predictable but potentially blocking.