Topics in this subject
Node.js 3 min read Updated 11 Aug 2026

Modules (CJS vs ESM)

Understanding require() vs import, and package.json configuration.

🧑‍🏫 Sabse pehle — simple mein samjho#

Jab hum backend code likhte hain to poora code ek single file mein nahi daal sakte. Humein code ko chhote-chhote hisson (Modules) mein todna padta hai. Node.js mein traditionally require() use hota tha (jise CommonJS ya CJS kehte hain). Lekin ab modern JavaScript (Frontend jaisa) aa gaya hai jisme import / export use hota hai (jise ES Modules ya ESM kehte hain). Node dono support karta hai, par tumhe configuration mein specify karna padta hai ki tum konsa use kar rahe ho.

CommonJS (CJS) - The Legacy Standard#

This is how Node.js worked from the beginning. It uses require() to load modules and module.exports to export them. It is synchronous, meaning it loads modules blocking the execution until they are resolved.

math.js (Exporting)

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

// Exporting multiple things as an object
module.exports = { add, subtract };

app.js (Importing)

// Importing
const math = require('./math.js');
console.log(math.add(5, 10));

// Or Destructuring
const { add } = require('./math.js');

ES Modules (ESM) - The Modern Standard#

This uses the modern import and export syntax. It is asynchronous and statically analyzable (which helps bundlers eliminate dead code).

To use ESM in Node.js, you must add "type": "module" to your package.json file.

package.json

{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module" 
}

math.js (Exporting)

// Named exports
export const add = (a, b) => a + b;

// Default export
export default function multiply(a, b) {
  return a * b;
}

app.js (Importing)

// Note: In Node.js ESM, you MUST include the file extension (.js)
import multiply, { add } from './math.js';

The package.json File#

This is the manifest of your Node.js project. It keeps track of your scripts and dependencies (the external libraries you install from npm).

  • dependencies: Libraries your app needs to run in production (e.g., express, mongoose). Installed via npm install express.
  • devDependencies: Libraries only needed during local development (e.g., nodemon, testing frameworks like jest). Installed via npm install -D nodemon.
  • scripts: Custom commands you can run via npm.
{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js" // Runs app and restarts on file changes
  }
}
// Run it in terminal: npm run dev

Global Variables in CJS vs ESM#

In CommonJS, you had access to __dirname and __filename to get the current file's directory path. In ESM, these global variables do not exist! You have to construct them manually using the url and path core modules.