seniorNode.js

Understanding the 'Module Wrapper Function' and CommonJS vs ESM

Updated May 4, 2026

Short answer

Node.js wraps CJS modules in a function to provide local variables like __dirname; ESM uses a top-level lexical scope and supports asynchronous loading.

Deep explanation

In CommonJS, your code is wrapped: (function(exports, require, module, __filename, __dirname) { ... }). This is why these variables exist without being defined. ES Modules (ESM) do not have this wrapper, which is why __dirname is missing. ESM is static, allowing for better 'Tree Shaking' (removing unused code), whereas CJS is dynamic. Senior devs must understand that ESM is now the standard for Node.js (v14+), though CJS is still pervasive in legacy packages.

Unlock with a Pro subscription to view this section.

View pricing

Real-world example

No real-world example available yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

Common mistakes

No common mistakes listed yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

Follow-up questions

No follow-up questions available yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

More Node.js interview questions

View all →