The Node.js runtime and module system
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Describe the Node event loop phases and why blocking code stalls every request.
- Choose between CommonJS and ES modules and explain require versus import resolution.
- Read process configuration from the environment instead of hardcoding it.
Overview
#Node.js runs JavaScript outside the browser on a single-threaded event loop with a libuv thread pool for I/O. A backend server keeps one process alive and handles many requests by never blocking that loop.
The event loop in one paragraph
Each iteration drains timers, then pending I/O callbacks, then runs setImmediate callbacks, then closes handles. Promise callbacks (microtasks) run between every phase. A long synchronous loop inside a handler delays every queued request, so CPU-heavy work belongs in a worker thread or a separate service.
Modules
CommonJS uses require and module.exports; ES modules use import and export. Node resolves bare specifiers through node_modules, and relative specifiers against the file path. In CommonJS __dirname exists; in ES modules you derive it from import.meta.url.
// config.js (CommonJS; default when package.json has no "type": "module")
const port = Number(process.env.PORT || 3000);
module.exports = { port };
// server.js (CommonJS)
const { port } = require('./config.js');
console.log('listening on', port);
// config.js (ES modules; package.json has "type": "module")
const port = Number(process.env.PORT || 3000);
export { port };
// server.js (ES modules)
import { port } from './config.js';
console.log('listening on', port);
Configuration and process
process.env holds environment variables as strings. Parse them once at startup, validate them, and fail fast when a required value is missing. Never commit secrets; the runtime injects them.
Common pitfalls
- Reading
process.env.PORTas a string and passing it where a number is required. - Mixing
requireandimportin one file without a build step. - Doing synchronous file reads on the request path and blocking the loop.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this print, and in what order?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconsole.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');Exercise 2Implement
Write a CommonJS config module (config.js, no "type": "module") that reads PORT and DATABASE_URL, defaults PORT to 3000, and throws when DATABASE_URL is missing.
starter.javascript// config.js (CommonJS) // export an object with port (number) and databaseUrl (string)Reveal the reference answer
reference.javascriptconst port = Number(process.env.PORT || 3000); const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { throw new Error('DATABASE_URL is required'); } module.exports = { port, databaseUrl };Authored expected output: With DATABASE_URL set, module exports { port: 3000, databaseUrl: '<value>' }. Without it, throws Error('DATABASE_URL is required').
Parse env values once at startup, coerce PORT to a number, and fail fast on a missing required secret so the process does not start in a broken state.
Common misconceptions
#- Node is multithreaded because it uses a thread pool: only libuv I/O and some crypto work is offloaded, JavaScript execution stays single-threaded.
- ES modules and CommonJS are interchangeable in one file: the loader differs and `require` is not available inside an ES module.
Follow-up practice
#- backend-databases-http-fundamentals
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.