Node.js Developer interview question · Most asked
What are the differences between CommonJS and ES modules in Node.js?
Summary
CommonJS uses require/module.exports, loads synchronously and is evaluated at runtime; ES modules use import/export, are statically analyzable, load asynchronously, support top-level await, and are strict mode by default. Node picks the format from .mjs/.cjs extensions or the package.json type field.
Longer Answer
ESM can import CommonJS (default import = module.exports). CommonJS can now require() synchronous ESM graphs in modern Node (22.12+/20.19+), but not ones using top-level await. In ESM, __dirname is replaced by import.meta.dirname/import.meta.filename (Node 20.11+). Packages use the exports field to define entry points and conditional exports for both formats.
Key Points
requirevsimporttype: moduleor.mjs/.cjs- Top-level await only in ESM
require(esm)supported in modern Nodeexportsfield for package entry points
More most-asked Node.js Developer questions
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are streams in Node.js and what is backpressure?
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- How does middleware work in Express?