Node.js runtime: event loop, modules, npm and config
Every Node.js service, CLI and build tool rests on the same four runtime basics: an event loop that decides when your callbacks run, a module system that decides how files find each other, npm projects that pin dependencies and define scripts, and environment variables that carry configuration into the process. This page covers all four with one running example, a small OrdersPortal back office that reads order files, prices them and talks to an orders API.
All samples were run with Node.js 22.23 (the oldest release line still in maintenance; Node.js 26 is the Active LTS line since October 2026 and Node.js 24 is in maintenance). Save each sample as .mjs (or use a package.json with "type": "module") and run it with node file.mjs.
Topics on this page
Section titled “Topics on this page”| Topic | Use it to understand |
|---|---|
| Event loop and async IO | Why one thread can serve thousands of connections, and what blocks it. |
| Modules | ES modules versus CommonJS, file extensions and interop. |
| npm and packages | package.json, lockfiles, scripts and dependency hygiene. |
| Environment variables | Loading .env files and validating configuration at startup. |
Event loop and async IO
Section titled “Event loop and async IO”Node.js runs your JavaScript on a single main thread. Slow work such as reading files, DNS lookups, TCP and HTTP is handed to the operating system or to libuv’s thread pool, and the main thread keeps running other callbacks until the result is ready. The event loop is the cycle that picks the next ready callback. It moves through phases: timers (setTimeout, setInterval), pending callbacks, poll (new I/O events, where most callbacks run), check (setImmediate) and close callbacks.
Between every callback Node.js drains two queues first: the process.nextTick queue and the promise microtask queue (.then, await continuations). In a CommonJS file the nextTick queue runs first. In an ES module the top-level code itself runs inside a promise job, so a promise callback queued there runs before a nextTick callback. That subtlety is one reason to avoid code that depends on the relative order of the two.
import { readFile } from 'node:fs';
console.log('sync: start handling order 1001');
process.nextTick(() => console.log('nextTick: emit "received" event'));Promise.resolve().then(() => console.log('microtask: order validated'));
readFile(import.meta.filename, () => { // Inside an I/O callback, setImmediate always runs before a 0 ms timer. setTimeout(() => console.log('timers phase: retry payment check'), 0); setImmediate(() => console.log('check phase: flush audit log')); console.log('poll phase: order file read');});
console.log('sync: end of script');Output:
sync: start handling order 1001sync: end of scriptmicrotask: order validatednextTick: emit "received" eventpoll phase: order file readcheck phase: flush audit logtimers phase: retry payment checkThe same file saved as .cjs (with require) prints the nextTick line before the microtask line. At the top level of a script, outside an I/O callback, the order of a 0 ms setTimeout and setImmediate is not guaranteed.
The model only works while each callback is short. CPU-heavy work holds the thread and every other request waits:
const started = Date.now();setTimeout(() => console.log(`health check answered after ${Date.now() - started} ms`), 10);
// Simulate a CPU-heavy report built inside a request handler.let total = 0;for (let i = 0; i < 3e8; i++) total += i % 7;console.log(`report finished after ${Date.now() - started} ms`);Output (timings vary by machine):
report finished after 529 mshealth check answered after 535 msThe 10 ms timer fired after more than half a second because the loop never got control back.
Pitfalls:
- CPU work in a request handler. Move heavy computation to
worker_threads, a child process or a job queue, or break it into chunks. - Synchronous APIs in hot paths.
readFileSync,execSyncandcrypto.pbkdf2Syncblock the loop; keep them to startup code and CLIs. - Recursive
process.nextTick. The nextTick queue is drained completely before I/O, so a callback that keeps scheduling itself starves the loop.
Modules
Section titled “Modules”Node.js has two module systems. ES modules (ESM) use import and export, are the JavaScript standard, load asynchronously and allow top-level await. CommonJS (CJS) uses require() and module.exports and was Node.js’s original system. A file is ESM if it ends in .mjs, or ends in .js and the nearest package.json has "type": "module"; .cjs is always CommonJS. New projects should use ESM.
ESM imports need the full relative path including the extension (./pricing.js), and __dirname does not exist; use import.meta.dirname and import.meta.filename (Node.js 20.11 and later). An ES module can import a CommonJS file: module.exports becomes the default import. Since Node.js 22.12, CommonJS can also require() an ES module without a flag, as long as that module and its imports contain no top-level await.
// src/pricing.js (package.json has "type": "module")export const currency = 'EUR';
export function lineTotal({ unitPrice, quantity }) { return Math.round(unitPrice * quantity * 100) / 100;}// src/vat.cjs - a CommonJS helper kept from an older codebaseconst VAT_RATE = 0.21;module.exports = { addVat: (amount) => Math.round(amount * (1 + VAT_RATE) * 100) / 100 };import { readFile } from 'node:fs/promises';import { join } from 'node:path';import { currency, lineTotal } from './pricing.js'; // ESM: extension requiredimport vat from './vat.cjs'; // CommonJS: module.exports is the default import
const lines = JSON.parse(await readFile(join(import.meta.dirname, 'order-1001.json'), 'utf8'));const net = lines.reduce((sum, line) => sum + lineTotal(line), 0);console.log(`Order 1001: ${lines.length} lines, net ${net.toFixed(2)} ${currency}, gross ${vat.addVat(net).toFixed(2)} ${currency}`);With order-1001.json containing two lines (2 × 19.99 and 4 × 5.50), node src/report.js prints:
Order 1001: 2 lines, net 61.98 EUR, gross 75.00 EURPitfalls:
- Missing extensions.
import './pricing'fails in ESM withERR_MODULE_NOT_FOUND; bundlers hide this, Node.js does not. - Named imports from CommonJS. Node.js detects named exports from simple
module.exportspatterns only; when in doubt import the default and destructure. - Use the
node:prefix for built-ins (node:fs,node:path) so a package with the same name can never shadow them.
npm and packages
Section titled “npm and packages”npm ships with Node.js and manages a project through package.json: its name, module type, supported Node.js versions (engines), dependencies and scripts. npm install resolves the dependency tree and records the exact versions in package-lock.json. Commit the lockfile and use npm ci in CI and Docker builds: it installs exactly what the lockfile says and fails if package.json and the lockfile disagree.
Keep runtime packages in dependencies and build or test tools in devDependencies (npm install -D). Version ranges use semantic versioning: ^5.3.0 accepts any 5.x at or above 5.3.0, ~5.3.0 only 5.3.x. Scripts give the team one vocabulary for common tasks; npm run report runs a script, and Node.js 22 adds node --run report, which starts faster because it skips npm’s own startup but does not run pre and post scripts.
{ "name": "orders-cli", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=22.12" }, "scripts": { "report": "node src/report.js", "report:dev": "node --env-file-if-exists=.env --watch src/report.js", "test": "node --test" }}npm ci # clean, lockfile-exact installnode --run report # or: npm run reportnpm outdated # what has newer versionsnpm audit # known vulnerabilities in the treeOutput of node --run report:
Order 1001: 2 lines, net 61.98 EUR, gross 75.00 EURThe built-in node --test runner and node --watch (stable since Node.js 22.0) cover what many projects used to install mocha and nodemon for.
Pitfalls:
npm installin CI. It may update the lockfile;npm ciis reproducible."private": trueforgotten on an application lets an accidentalnpm publishpush it to the public registry.- Install scripts run arbitrary code. Review new dependencies, prefer well-maintained packages, and consider
npm ci --ignore-scriptswhere the build allows it.
Environment variables
Section titled “Environment variables”Configuration that changes between environments (ports, API URLs, timeouts, feature flags, secrets) belongs in environment variables, read through process.env. Every value is a string or undefined, so parse numbers and booleans explicitly. Node.js can load a .env file itself: node --env-file=.env app.js, --env-file-if-exists for optional files, or process.loadEnvFile() from code. Both became stable in Node.js 22.21 and 24.10, which removes the need for the dotenv package in most apps. A variable already set in the real environment wins over the file.
Read and validate configuration once, at startup, in one module, and fail fast with a clear message. The rest of the code imports a typed, frozen object instead of touching process.env.
// config.mjs - run with: node --env-file=.env config.mjsfunction required(name) { const value = process.env[name]; if (value === undefined || value === '') throw new Error(`Missing required environment variable ${name}`); return value;}
function integer(name, fallback) { const raw = process.env[name] ?? String(fallback); const value = Number.parseInt(raw, 10); if (!Number.isInteger(value) || value <= 0) throw new Error(`${name} must be a positive integer, got "${raw}"`); return value;}
export const config = Object.freeze({ port: integer('PORT', 3000), ordersApiUrl: new URL(required('ORDERS_API_URL')).href, // throws on a malformed URL requestTimeoutMs: integer('REQUEST_TIMEOUT_MS', 5000), splitShipments: process.env.FEATURE_SPLIT_SHIPMENTS === 'true', environment: process.env.NODE_ENV ?? 'development',});
console.log(config);# .env - local development only, listed in .gitignorePORT=8080ORDERS_API_URL=https://api.example.test/ordersREQUEST_TIMEOUT_MS=2500FEATURE_SPLIT_SHIPMENTS=trueOutput:
{ port: 8080, ordersApiUrl: 'https://api.example.test/orders', requestTimeoutMs: 2500, splitShipments: true, environment: 'development'}Running PORT=9090 node --env-file=.env config.mjs prints port: 9090, and running without the file stops at once with Error: Missing required environment variable ORDERS_API_URL. Commit a .env.example with placeholder values so new developers know what to set; in production set variables through the hosting platform and keep secrets in a secret store such as Azure Key Vault, AWS Secrets Manager or Kubernetes Secrets.
Pitfalls:
Boolean(process.env.FLAG)istruefor the string"false"; compare with'true'explicitly.- Committing
.env. Add it to.gitignorebefore the first commit; a secret pushed once must be rotated. - Reading
process.enveverywhere scatters defaults and makes missing values surface as odd runtime errors far from startup.
Choosing between them
Section titled “Choosing between them”| Situation | Reach for |
|---|---|
| Many slow network or file operations | The event loop as is: async/await and non-blocking APIs. |
| Heavy CPU work (image resizing, large reports) | worker_threads, a separate service or a queue. |
| A new project or library | ES modules with "type": "module". |
| An existing CommonJS codebase | Keep CJS, require() new ESM packages (22.12+) and migrate file by file. |
| Local configuration | --env-file plus a validating config module. |
Interview questions
Section titled “Interview questions”What happens when a Node.js server receives 1,000 concurrent requests that each query a database?
Each handler starts its query and returns to the event loop at the first await. The queries run concurrently in the database driver and the operating system; as results arrive, the poll phase runs the continuations. One thread handles all 1,000 because the time is spent waiting, not computing.
What is the difference between process.nextTick, a resolved promise and setImmediate?
nextTick and promise callbacks run before the loop continues, after the current operation; setImmediate runs in the check phase of the next loop iteration, after pending I/O has been polled. In CommonJS nextTick runs before promise callbacks; in ESM top-level code the order can differ.
Why is package-lock.json committed, and why use npm ci?
The lockfile records the exact resolved version of every transitive dependency, so every machine installs the same tree. npm ci installs only from the lockfile and fails on drift, which makes builds reproducible.
Can CommonJS code use an ESM-only package?
Yes, from Node.js 22.12 require() loads an ES module synchronously as long as its graph has no top-level await. On older versions, use dynamic import(), which returns a promise.
Senior scenario: p99 latency of an order API jumps to seconds during month-end, while CPU is at 100% on one core. How do you investigate and fix it?
A single saturated core with rising latency suggests event-loop blocking. Measure loop delay with perf_hooks.monitorEventLoopDelay(), take a CPU profile (node --cpu-prof) during the spike and look for synchronous work such as large JSON.parse, report generation or sync crypto. Move that work to a worker pool or an asynchronous job, add pagination or streaming for large payloads, and alert on event-loop delay rather than only on CPU.
Related pages
Section titled “Related pages”- Node.js overview for the section reading path.
- Files and streams for
fs/promises, paths and stream pipelines. - HTTP, Express and REST APIs for building services on this runtime.
- Node.js interview questions for broader practice.
Official references
Section titled “Official references”- The Node.js event loop
- Node.js 22 modules: ECMAScript modules and CommonJS modules
- Node.js 22 command-line options (
--env-file,--run,--watch,--test) - Node.js 22
process.loadEnvFile() - npm CLI documentation (
npm ci,package.json, semver) - Node.js release schedule