QA
Beginner LevelNode JS

Compare CommonJS (require/module.exports) vs ES Modules (import/export) in Node.js.

❓ Interview Prompt: Explain CommonJS (synchronous loading, require) vs ES Modules (asynchronous loading, static import/export, top-level await).

Node.js supports two module formats:

1. CommonJS (CJS):

•
Legacy default format ('.cjs' or '"type": "commonjs"').
•
Synchronous loading via 'require()' and 'module.exports'.
•
Evaluates dynamically at runtime.

2. ES Modules (ESM):

•
Modern standard format ('.mjs' or '"type": "module"').
•
Asynchronous static loading via 'import' and 'export'.
•
Supports Top-Level Await!

Code Implementation Example

javascript
// CommonJS (CJS)
const fs = require('fs');
module.exports = { fetchData };

// ES Modules (ESM)
import fs from 'node:fs';
export { fetchData };
// Top-Level Await supported in ESM!
const data = await fs.promises.readFile('config.json', 'utf8');
💡Comparing CommonJS require syntax with ES Modules import syntax.
🎯 Interview Key Takeaway

Use ES Modules for modern Node.js applications to support static analysis, tree-shaking, and top-level await.

#CommonJS#ESM#Modules#import#require#Beginner
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?