Skip to content
BackendNodeJs

2. NPM Packages कैसे इंस्टॉल करें? Modules (ESM vs CommonJS) 2026

April 17, 2026 14 min read

नमस्ते दोस्तों! 🙏
स्वागत है The Easy Master पर!

क्या तुमने कभी सोचा है – Node.js mein packages install kaise karte hain? Aur require vs import – kya antar hai?

Jab tum Node.js project banate ho, toh tum kuch bhi scratch se nahi likhte – tum packages use karte ho:

  • Express.js (server banane ke liye)
  • Mongoose (database ke liye)
  • Bcrypt (password hash karne ke liye)
  • JSON Web Token (authentication ke liye)

NPM packages install modules Hindi में समझना बहुत जरूरी है क्योंकि:

  • 2M+ packages available hai NPM par
  • Har Node.js project packages use karta hai
  • ESM vs CommonJS – modern vs old module system
  • Interview questions mein pakka puchega!

Aaj kya seekhoge?

TopicKya Seekhega?
NPM Kya Hai?Node Package Manager introduction
NPM CommandsInstall, uninstall, update, audit
package.jsonDependencies manage karna
node_modulesFolder structure samjhena
CommonJSrequire() module system
ESM (ES Modules)import/export modern system
ESM vs CommonJSComparison aur kab kya use karein
TypeScript ModulesTS mein module config

Kya tumhe pata hai?
NPM par 2 million+ packages available hain – aur har din 1000+ naye packages add hote hain! 😮

तो चलिए शुरू करते हैं – NPM packages install modules Hindi सीखने का सफर! 🚀

Table of Contents

1. NPM क्या है? Node.js Package Manager Introduction

NPM ka full form hai Node Package Manager – ye Node.js ka official package manager hai।

NPM Kya Karta Hai?

FeatureExplanation
Packages InstallExpress, Mongoose, React – sab NPM se install
Version ManagementPackage ka specific version install karna
Dependencies Trackingpackage.json mein sab track rehta hai
Sharing CodeApna package publish kar sakte ho
Scripts Runnpm start, npm test jaise scripts

NPM ke 3 Main Parts:

Code
┌─────────────────────────────────────────────┐
│                  NPM                        │
├─────────────────────────────────────────────┤
│  1. Website – packages search karne ke liye  │
│     (https://www.npmjs.com)                  │
│                                              │
│  2. CLI – command line tool                  │
│     (npm install, npm start)                 │
│                                              │
│  3. Registry – packages ka database           │
│     (2M+ packages stored here)               │
└─────────────────────────────────────────────┘

NPM packages install modules Hindi mein aaj hum NPM commands aur modules (CommonJS vs ESM) dono cover karenge।

2. NPM Installation and Setup

Step 1: Node.js Install Karna

NPM Node.js ke saath automatically install ho jata hai।

Code
# Check if Node.js is installed
node --version
# Output: v24.0.0

# Check if NPM is installed
npm --version
# Output: 10.x.x

Step 2: Pehla Project Setup

Code
# Create project folder
mkdir my-npm-project
cd my-npm-project

# Initialize NPM project
npm init

# OR quick init (skip questions)
npm init -y

Step 3: package.json Created

npm init -y run karne se ye file banti hai:

Code
{
  "name": "my-npm-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

3. Pehla Package Install Karna

Install a Package:

Code
# Install express (production dependency)
npm install express

# Install nodemon (development dependency)
npm install -D nodemon

# Install globally
npm install -g npm-check-updates

After Installation:

Code
# package.json now has dependencies
{
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  }
}

Using Installed Package:

Code
// index.js
const express = require('express');

const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.json({ message: 'Hello from Express!' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Important NPM Commands:

CommandKarta Kya Hai?
npm installpackage.json ke sab packages install
npm install expressExpress install aur package.json mein add
npm install -D nodemonDev dependency install
npm install -g nodemonGlobally install (system level)
npm uninstall expressPackage remove karna
npm updateSab packages update
npm outdatedOutdated packages dikhana
npm auditSecurity vulnerabilities check
npm audit fixVulnerabilities auto fix

4. package.json – Project Ka Heart

package.json project ki identity card hai – ye batata hai ki project mein kya-kya hai।

Complete package.json Example:

Code
{
  "name": "ecommerce-api",
  "version": "1.0.0",
  "description": "E-commerce API built with Node.js and Express",
  "main": "server.js",
  "type": "module",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest",
    "build": "npm run lint && npm run test",
    "lint": "eslint ."
  },
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^8.0.0",
    "dotenv": "^16.3.1",
    "bcrypt": "^5.1.1",
    "jsonwebtoken": "^9.0.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.0",
    "jest": "^29.7.0",
    "eslint": "^8.56.0"
  },
  "keywords": ["api", "ecommerce", "nodejs", "express"],
  "author": "Rahul Sharma",
  "license": "MIT",
  "engines": {
    "node": ">=18.0.0",
    "npm": ">=9.0.0"
  }
}

Version Numbers Explained:

SymbolMeaningExample
^4.18.2Compatible version (4.x.x)^4.18.2 means 4.18.2, 4.19.0, 4.20.0
~4.18.2Approximately equivalent (4.18.x)~4.18.2 means 4.18.2, 4.18.3, 4.18.9
4.18.2Exact versionSirf 4.18.2 install hoga
*Latest versionAlways latest (risky!)
>=4.0.0Greater than or equal4.0.0, 5.0.0, 6.0.0

5. node_modules – Packages Store Hain Yahan

node_modules Folder Structure:

Code
my-project/
├── node_modules/          # 📦 Sab packages yahan install hote hain
│   ├── express/           # Express package
│   │   ├── index.js
│   │   ├── package.json
│   │   └── lib/
│   ├── mongoose/          # Mongoose package
│   ├── dotenv/            # Dotenv package
│   └── ... (hundreds of files)
├── package.json
├── package-lock.json
└── index.js

package-lock.json Kya Hai?

  • Exact versions track karta hai
  • Dependency tree store karta hai
  • Auto-generated – manually edit mat karo
  • Git commit karo (taaki exact versions sabko mile)
Code
// package-lock.json (auto-generated)
{
  "name": "my-project",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "node_modules/express": {
      "version": "4.18.2",
      "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
      "integrity": "sha512-...",
      "dependencies": {
        "accepts": "~1.3.8",
        "body-parser": "1.20.1"
      }
    }
  }
}

node_modules ko Git Ignore Karo:

Code
# .gitignore
node_modules/
.env
.DS_Store

6. CommonJS Modules: require() का पुराना जमाना

CommonJS Node.js ka default module system hai – require() aur module.exports use karta hai।

Exporting in CommonJS:

Code
// math.js (CommonJS)
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

const PI = 3.14159;

// Export multiple things
module.exports = {
  add,
  subtract,
  PI
};

// OR export one by one
// exports.add = add;
// exports.subtract = subtract;

Importing in CommonJS:

Code
// app.js (CommonJS)
const math = require('./math.js');

console.log(math.add(5, 3));     // 8
console.log(math.subtract(5, 3)); // 2
console.log(math.PI);             // 3.14159

// Destructuring
const { add, subtract, PI } = require('./math.js');
console.log(add(10, 5)); // 15

Built-in Modules:

Code
// Node.js built-in modules – no install needed!
const fs = require('fs');        // File system
const path = require('path');    // Path utilities
const http = require('http');    // HTTP server
const crypto = require('crypto'); // Cryptography
const os = require('os');        // Operating system

console.log(os.platform());      // 'win32' or 'linux'
console.log(path.join('folder', 'file.txt')); // 'folder/file.txt'

Third-party Modules (Installed via NPM):

Code
// Third-party modules – need npm install first!
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');

// Use them
const app = express();

7. ESM (ES Modules) – Modern Tarika

ESM (ECMAScript Modules) JavaScript ka official module system hai – import/export use karta hai।

Enabling ESM in Node.js:

Method 1: "type": "module" in package.json

Code
// package.json
{
  "name": "my-project",
  "type": "module",  // ✅ Enable ESM
  "dependencies": {
    "express": "^4.18.2"
  }
}

Method 2: .mjs file extension

Code
// math.mjs – ESM file
export function add(a, b) {
  return a + b;
}

export const PI = 3.14159;

Exporting in ESM:

Code
// math.js (ESM)
// Named exports
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export const PI = 3.14159;

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

Importing in ESM:

Code
// app.js (ESM)
// Named imports
import { add, subtract, PI } from './math.js';

// Default import
import multiply from './math.js';

// Import everything as object
import * as math from './math.js';

console.log(add(5, 3));        // 8
console.log(multiply(5, 3));   // 15
console.log(math.PI);           // 3.14159

Dynamic Imports (Lazy Loading):

Code
// ESM – dynamic import (lazy loading)
const module = await import('./math.js');
console.log(module.add(5, 3));

// Conditional import
if (condition) {
  const { encrypt } = await import('./crypto.js');
  encrypt(data);
}

Importing JSON in ESM:

Code
// ESM – need import assertion
import data from './config.json' assert { type: 'json' };

console.log(data.apiUrl);

8. ESM vs CommonJS – Comparison

FeatureCommonJS (require)ESM (import/export)
Syntaxconst x = require('x')import x from 'x'
DefaultNode.js defaultNeed "type": "module"
LoadingSynchronousAsynchronous
Tree Shaking❌ No✅ Yes
Top-level await❌ No✅ Yes
Browser support❌ No✅ Yes
Dynamic importsrequire()import()
__dirname✅ Available❌ Need import.meta.url
File extension.js.js with "type": "module" or .mjs

Code Comparison:

Code
// ========== CommonJS ==========
// math.cjs
function add(a, b) { return a + b; }
module.exports = { add };

// app.cjs
const { add } = require('./math.cjs');
console.log(add(2, 3));

// ========== ESM ==========
// math.mjs
export function add(a, b) { return a + b; }

// app.mjs
import { add } from './math.mjs';
console.log(add(2, 3));

__dirname in ESM:

Code
// CommonJS – __dirname available
console.log(__dirname); // /home/user/project

// ESM – need to create __dirname
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

console.log(__dirname); // /home/user/project

When to Use What:

Use CommonJS If…Use ESM If…
Old Node.js projectNew project (2024+)
Need __dirname easilyBrowser + Node.js same code
Many legacy packagesNeed tree shaking
Simpler setupNeed top-level await

9. TypeScript Modules – tsconfig.json Setup

Installing TypeScript:

Code
npm install -D typescript @types/node
npx tsc --init

tsconfig.json for CommonJS:

Code
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",      // Output CommonJS
    "moduleResolution": "node",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

tsconfig.json for ESM:

Code
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",         // Output ESM
    "moduleResolution": "bundler",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

TypeScript Code Example:

Code
// src/math.ts (TypeScript)
export function add(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14159;

// src/app.ts
import { add, PI } from './math.js'; // Note: .js extension in import!

console.log(add(5, 3));
console.log(PI);

package.json scripts for TypeScript:

Code
{
  "scripts": {
    "build": "tsc",
    "start": "node dist/app.js",
    "dev": "tsx watch src/app.ts"
  },
  "devDependencies": {
    "typescript": "^5.3.0",
    "tsx": "^4.6.0",
    "@types/node": "^20.10.0"
  }
}

Must-Have Packages for Backend:

PackagePurposeInstall Command
expressWeb frameworknpm install express
mongooseMongoDB ODMnpm install mongoose
dotenvEnvironment variablesnpm install dotenv
bcryptPassword hashingnpm install bcrypt
jsonwebtokenJWT authenticationnpm install jsonwebtoken
corsCross-origin requestsnpm install cors
helmetSecurity headersnpm install helmet
morganHTTP loggingnpm install morgan
joiValidationnpm install joi
nodemailerEmail sendingnpm install nodemailer

Must-Have Dev Dependencies:

PackagePurposeInstall Command
nodemonAuto-restart servernpm install -D nodemon
jestTesting frameworknpm install -D jest
eslintCode lintingnpm install -D eslint
prettierCode formattingnpm install -D prettier
typescriptTypeScript supportnpm install -D typescript

Complete Example with Multiple Packages:

Code
# Create project
mkdir my-api
cd my-api
npm init -y

# Install all dependencies
npm install express mongoose dotenv bcrypt jsonwebtoken cors helmet morgan joi

# Install dev dependencies
npm install -D nodemon jest eslint prettier
Code
// server.js (ESM style)
import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';

dotenv.config();

const app = express();

// Middleware
app.use(express.json());
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.json({ message: 'API is running!' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

11. Common Mistakes + Solutions

Mistake 1: import in CommonJS project

Code
// ❌ Error: Cannot use import statement outside a module
import express from 'express';

// ✅ Solution – use require
const express = require('express');

// OR set "type": "module" in package.json

Mistake 2: Forgetting ./ for local files

Code
// ❌ Error – Node.js thinks it's a core module
const math = require('math.js');

// ✅ Correct – local file needs ./
const math = require('./math.js');

Mistake 3: Missing file extension in ESM

Code
// ❌ Error – ESM needs file extension
import { add } from './math';

// ✅ Correct
import { add } from './math.js';

Mistake 4: Not adding "type": "module" for ESM

Code
// ❌ ESM code but package.json has no "type": "module"
import express from 'express'; // Error!

// ✅ Add to package.json
{
  "type": "module"
}

Mistake 5: Installing wrong package

Code
# ❌ Wrong – no such package
npm install bcryptjs-instead

# ✅ Check exact name on npmjs.com first
npm install bcrypt

Mistake 6: Not saving to package.json

Code
# ❌ Package installs but not saved
npm install express

# ✅ Save to dependencies
npm install express --save

# ✅ Save to devDependencies
npm install nodemon --save-dev

12. Quick Cheat Sheet

NPM Commands:

CommandPurpose
npm init -yCreate package.json
npm installInstall all dependencies
npm install expressInstall package
npm install -D nodemonInstall dev dependency
npm install -g npmInstall globally
npm uninstall expressRemove package
npm updateUpdate all packages
npm outdatedCheck outdated packages
npm auditCheck vulnerabilities
npm run devRun custom script

CommonJS vs ESM:

CommonJSESM
const x = require('x')import x from 'x'
module.exports = {}export default {}
exports.fn = () => {}export const fn = () => {}
require('./file')import './file.js'
SynchronousAsynchronous
No top-level awaitTop-level await ✅

package.json Scripts:

Code
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest",
    "build": "tsc",
    "lint": "eslint .",
    "format": "prettier --write ."
  }
}

13. FAQ

Q1: NPM packages install modules Hindi में सबसे important command kya hai?
npm init -y (project start) aur npm install express (package install) – ye do commands sabse zyada use hoti hain।

Q2: npm install aur npm ci mein kya antar hai?
npm install package.json ke hisaab se latest compatible versions install karta hai। npm ci package-lock.json ke exact versions install karta hai – CI/CD pipelines ke liye।

Q3: dependencies vs devDependencies – kya antar hai?
dependencies – production mein bhi chahiye (express, mongoose)। devDependencies – sirf development mein (nodemon, jest, eslint)。

Q4: CommonJS vs ESM – 2026 mein kya use karein?
New projects mein ESM use karo – ye future hai। Old projects maintain kar rahe ho toh CommonJS bhi chalega।

Q5: node_modules folder ko git mein commit karna chahiye?
Nahi! .gitignore mein daalo – bahut bada folder hai (100MB+), aur packages reinstalled ho sakte hain।

Q6: package-lock.json commit karna chahiye?
Haan! Isse sab developers ko exact same versions milte hain – production mein surprise bugs nahi aate।

Q7: Global packages kyun avoid karein?
Global packages project-specific nahi hote – team members ke paas same version nahi ho sakta। Project-specific install karo।

Q8: NPM vs Yarn vs pnpm – kya use karein?
NPM default hai (Node.js ke saath aata hai)। Yarn fast tha pehle, ab NPM bhi fast hai। pnpm disk space save karta hai। NPM 2026 mein recommended hai।

Q9: Security vulnerabilities kaise check karein?
npm audit – vulnerabilities dikhata hai। npm audit fix – auto fix karta hai। Always run before production deploy!

Q10: Kya ESM mein __dirname available hai?
Nahi, but create kar sakte ho:

Code
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __dirname = dirname(fileURLToPath(import.meta.url));

14. Conclusion

बहुत बढ़िया दोस्तों! आज हमने NPM packages install modules Hindi को पूरी detail में समझा।

Quick Recap:

ConceptKey Takeaway
NPMNode.js package manager – 2M+ packages
package.jsonProject ki identity card
CommonJSrequire() – old but still used
ESMimport/export – modern, future
node_modulesPackages store hota hai yahan

Mera personal experience:

जब मैंने पहली बार NPM seekha, toh require vs import se bohot confuse tha। Ek project mein CommonJS tha, dusre mein ESM – error aate the। Ab samajh aa gaya hai – dono ka use case alag hai।

Tum bhi ye steps follow karo:

  1. ✅ npm init -y se project start karo
  2. ✅ Kuch packages install karo (express, nodemon)
  3. ✅ CommonJS mein module export/import karo
  4. ✅ "type": "module" se ESM try karo
  5. ✅ npm audit security check karo

अब तुम्हारी बारी है!

नीचे comment में बताओ:

  1. तुम CommonJS use karoge ya ESM? क्यों?
  2. तुम्हें कौन सा NPM command sabse useful laga?
  3. अगला topic क्या चाहिए? (Express.js Deep Dive? MongoDB? JWT Authentication?)

The Easy Master पर बने रहो। Happy NPM-ing! 📦🚀


Resources

Additional Resources

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *