Skip to content

Interview PrepAsync · Core

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'
CommonJSES Modules
Syntaxrequire, module.exportsimport, export
When loadedAt runtime, when require runsBefore running, from static analysis
SynchronousYesLoading is asynchronous
Can import conditionallyYes: if (x) require(…)Static imports no; use import() (question 67)
Exports areA copied value or objectLive bindings: you see later changes
Top-level awaitNoYes
Tree shakingHardYes
this at top levelmodule.exportsundefined
Strict modeOnly if declaredAlways (question 6)
__dirname, __filenameAvailableUse import.meta.dirname and import.meta.filename
Works in browsersNoYes

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 variable

With 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)
  1. 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.
  2. A computed path, here picking a language file at runtime.

Where it is used:

UseExample
Code splitting in front endsReact.lazy(() => import('./AdminPage'))
Optional or heavy dependenciesImage processing loaded only for upload routes
PluginsLoading modules listed in a config file
ESM from CommonJSconst { 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) { /* ... */ }
  1. If orders.ts is loaded first, it starts evaluating, hits its import of notifications.ts, and evaluates that module before its own lines run. At that point ORDER_STATUSES does not have a value yet, so this line throws ReferenceError: 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:

  1. Move the shared piece into a third module: put ORDER_STATUSES in order-statuses.ts, imported by both.
  2. Depend on an interface, not the other module: pass notifyCustomer into shipOrder as a parameter, or through dependency injection.
  3. 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.

checkoutemit('order-placed')orderEventsan EventEmitter① send receipt② update stock③ record analytics
Shout once, everyone who cares hears it. The checkout code only emits one event. The emitter calls each listener in the order it was registered, one after another, on the same call stack.
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)
}
  1. on registers a listener. Any part of the program can subscribe without the checkout code knowing.
  2. once runs a single time, then removes itself.
  3. 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.
  4. emit calls every listener synchronously, in registration order, before returning.
  5. This line runs only after all listeners have finished. If a listener does slow synchronous work, checkout waits for it.

Important behaviours:

BehaviourDetail
SynchronousListeners run immediately inside emit, not later
Async listenersAn async listener's promise is ignored; its rejection is unhandled unless you handle it (question 59)
OrderingRegistration order; prependListener puts one first
MemoryForgetting off leaks the listener and its closure (question 14)
WarningMore 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 event

Event-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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet