Appearance
Modules and Events
66. What is the difference between CommonJS and ES Modules?
The short answer
CommonJS is Node.js's original module system: you load with require() and export with module.exports, and loading happens synchronously at runtime, when the line runs. ES Modules are the standard JavaScript module system: you use import and export, which are static, so tools know every dependency before running anything. That enables tree shaking, top-level await and the same syntax in browsers and Node.js. New code should use ES Modules.
The same module, both ways:
ts
// CommonJS: pricing.cjs
const TAX = 0.2
function withTax(amount) { return amount * (1 + TAX) }
module.exports = { withTax }
// used as
const { withTax } = require('./pricing.cjs')ts
// ES Module: pricing.mjs, or .js with "type": "module" in package.json
const TAX = 0.2
export function withTax(amount: number) { return amount * (1 + TAX) }
// used as
import { withTax } from './pricing.mjs'| CommonJS | ES Modules | |
|---|---|---|
| Syntax | require, module.exports | import, export |
| When loaded | At runtime, when require runs | Before running, from static analysis |
| Synchronous | Yes | Loading is asynchronous |
| Can import conditionally | Yes: if (x) require(…) | Static imports no; use import() (question 67) |
| Exports are | A copied value or object | Live bindings: you see later changes |
Top-level await | No | Yes |
| Tree shaking | Hard | Yes |
this at top level | module.exports | undefined |
| Strict mode | Only if declared | Always (question 6) |
__dirname, __filename | Available | Use import.meta.dirname and import.meta.filename |
| Works in browsers | No | Yes |
Live bindings, the subtle difference:
ts
// counter.mjs
export let count = 0
export function increment() { count += 1 }
// app.mjs
import { count, increment } from './counter.mjs'
increment()
console.log(count) // 1: the import sees the updated variableWith CommonJS, const { count } = require('./counter.cjs') copies the value 0 at that moment, and it never changes.
How Node.js decides which one a file is: .mjs files are ES Modules, .cjs files are CommonJS, and .js files follow the nearest package.json's "type" field, "module" or "commonjs". Recent Node.js versions can also require() an ES Module that has no top-level await, which has removed most of the pain of mixing the two. The Node.js module goes into the details of loading and resolution.
Tree shaking means a bundler removes exports nobody imports. It works with ES Modules because import { withTax } is visible without running the code.
67. What is dynamic import(), and when is it useful?
The short answer
import('./module.js') is a function-like expression that loads a module at runtime and returns a promise of the module's exports. Unlike a static import statement, it can be used anywhere: inside an if, inside a function, with a computed path. It is used to load code only when it is needed, such as a heavy PDF library on the page that exports invoices, which makes the first load faster. It also lets CommonJS code load ES Modules.
ts
async function downloadInvoice(orderId: string) {
const { renderInvoicePdf } = await import('./invoice-pdf.js') // (1)
const pdf = await renderInvoicePdf(orderId)
return pdf
}
const locale = navigator.language.startsWith('de') ? 'de' : 'en'
const messages = await import(`./i18n/${locale}.js`) // (2)- Loaded on demand. The PDF library is downloaded or read from disk only when someone actually exports an invoice. Bundlers like Vite turn each dynamic import into a separate file, called a chunk.
- A computed path, here picking a language file at runtime.
Where it is used:
| Use | Example |
|---|---|
| Code splitting in front ends | React.lazy(() => import('./AdminPage')) |
| Optional or heavy dependencies | Image processing loaded only for upload routes |
| Plugins | Loading modules listed in a config file |
| ESM from CommonJS | const { nanoid } = await import('nanoid') inside an async function |
Cost: the first call pays the loading time, so do not put a dynamic import on a hot path that runs on every request. After the first time, the module is cached, and later calls return the same module object.
68. What happens with circular imports?
The short answer
A circular import is when module A imports module B and B, directly or through others, imports A. JavaScript does not crash on this. While A is still being evaluated, B receives A in its unfinished state. With ES Modules, B's imports from A are live bindings that exist but are in their temporal dead zone until A finishes, so touching them too early throws a ReferenceError. With CommonJS, B gets A's half-filled module.exports, often an empty object, so values are silently undefined.
ts
// orders.ts
import { notifyCustomer } from './notifications'
export const ORDER_STATUSES = ['placed', 'paid', 'shipped']
export function shipOrder(id: string) { notifyCustomer(id, 'shipped') }
// notifications.ts
import { ORDER_STATUSES } from './orders'
console.log(ORDER_STATUSES.length) // (1)
export function notifyCustomer(id: string, status: string) { /* ... */ }- If
orders.tsis loaded first, it starts evaluating, hits its import ofnotifications.ts, and evaluates that module before its own lines run. At that pointORDER_STATUSESdoes not have a value yet, so this line throwsReferenceError: Cannot access 'ORDER_STATUSES' before initialization.
Why it is only sometimes a problem: reading the import inside a function that runs later is fine, because by then both modules have finished loading. The trouble is reading an imported value at the top level of a module, during loading.
Fixes, in order of preference:
- Move the shared piece into a third module: put
ORDER_STATUSESinorder-statuses.ts, imported by both. - Depend on an interface, not the other module: pass
notifyCustomerintoshipOrderas a parameter, or through dependency injection. - Delay the access: use the import only inside functions, never at the top level.
Finding cycles: tools such as madge --circular src/ or the ESLint rule import/no-cycle list them. A cycle is usually a sign that two modules have their responsibilities mixed up.
69. What is EventEmitter, and how does event-driven programming work in JavaScript and Node.js?
The short answer
Event-driven programming means parts of a program react to named events instead of calling each other directly: one part emits "order placed", and any number of listeners respond. In Node.js, the EventEmitter class provides this: on registers a listener, emit triggers an event and calls its listeners synchronously in the order they were added, once listens a single time, and off removes a listener. Streams, servers and sockets in Node.js are all built on it.
ts
import { EventEmitter } from 'node:events'
type OrderPlaced = { orderId: string; email: string; skus: string[] }
const orderEvents = new EventEmitter()
orderEvents.on('order-placed', (o: OrderPlaced) => sendReceipt(o.email)) // (1)
orderEvents.on('order-placed', (o: OrderPlaced) => reserveStock(o.skus))
orderEvents.once('order-placed', () => console.log('first order today!')) // (2)
orderEvents.on('error', (err) => logger.error({ err }, 'order event failed')) // (3)
function checkout(order: OrderPlaced) {
saveOrder(order)
orderEvents.emit('order-placed', order) // (4)
console.log('checkout returns') // (5)
}onregisters a listener. Any part of the program can subscribe without the checkout code knowing.onceruns a single time, then removes itself.- An
'error'listener. Emitting'error'with no listener for it makes the emitter throw, which can crash the process. Always listen for'error'on emitters that can fail. emitcalls every listener synchronously, in registration order, before returning.- This line runs only after all listeners have finished. If a listener does slow synchronous work, checkout waits for it.
Important behaviours:
| Behaviour | Detail |
|---|---|
| Synchronous | Listeners run immediately inside emit, not later |
| Async listeners | An async listener's promise is ignored; its rejection is unhandled unless you handle it (question 59) |
| Ordering | Registration order; prependListener puts one first |
| Memory | Forgetting off leaks the listener and its closure (question 14) |
| Warning | More than 10 listeners for one event prints a possible-leak warning |
Awaiting an event once:
ts
import { once } from 'node:events'
const [order] = await once(orderEvents, 'order-placed') // a promise for the next eventEvent-driven inside a process versus between services. EventEmitter connects parts of one process, in memory. Nothing survives a crash, and there are no retries. For events between services, such as "order placed" reaching the warehouse system, you need a message broker such as Kafka or RabbitMQ, covered in the architecture module.
In the browser, the same idea is EventTarget, with addEventListener and dispatchEvent, and DOM events add bubbling through parent elements.