Skip to content
BackendNodeJs

1. Node.js क्या है? 2026 में अपना पहला Backend Server बनाएँ

April 17, 2026 15 min read

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

क्या तुमने कभी सोचा है – React frontend to bana liya, backend kaise banayein?

Frontend mein jo data dikhta hai (users, products, posts) – wo kahin se aata hai। Wo “kahin” hai backend server – jo database se data laata hai, APIs banata hai, aur frontend ko data bhejta hai।

Node.js Kya Hai? 2026 Mein Pehla Backend Server Banaye में समझना बहुत जरूरी है क्योंकि:

  • JavaScript backend – ek hi language (JS) frontend + backend dono mein
  • Fast aur Scalable – Non-blocking I/O, millions of users handle kar sakta hai
  • NPM ecosystem – 2M+ packages available
  • Job market – 80%+ companies Node.js use karti hain

Aaj kya seekhoge?

TopicKya Seekhega?
Node.js Kya Hai?Introduction, history, architecture
Why Node.js?Benefits, use cases, companies using
InstallationNode.js + npm install
Pehla ServerHTTP module se basic server
Express.jsPopular framework for APIs
REST APIGET, POST, PUT, DELETE endpoints
DeploymentServer deploy kaise karein

Kya tumhe pata hai?
Node.js non-blocking architecture use karta hai – ek thread millions of connections handle kar sakta hai। Traditional servers (PHP, Ruby) har connection ke liye alag thread banate hain!

तो चलिए शुरू करते हैं – Node.js backend server Hindi सीखने का सफर! 🚀

Table of Contents

1. Node.js क्या है? – Introduction

Node.js क्या है? simple words mein:

Node.js ek runtime environment hai jo JavaScript ko server-side run karne deta hai।

Pehle JavaScript sirf browser mein chalti thi (frontend ke liye)। Node.js ne JavaScript ko bahar laaya – ab tum JavaScript se backend, desktop apps, mobile apps, CLI tools, sab kuch bana sakte ho!

Node.js History:

YearEvent
2009Ryan Dahl ne Node.js banaya
2011npm (Node Package Manager) launched
2015Node.js Foundation formed
2018Node.js 10 (LTS)
2022Node.js 18 (fetch API, test runner)
2024Node.js 22 (native WebSocket, watch mode)
2026Node.js 24 (current LTS)

Who Uses Node.js?

CompanyUse Case
NetflixFast streaming, 70% faster startup
PayPalFrontend + backend same language
LinkedInMobile backend (20x faster)
UberReal-time ride tracking
NASADatabase access for EVA suits

Node.js backend server Hindi mein aaj hum inhi concepts ko detail mein samjhenge।

2. Why Node.js? – Benefits and Use Cases

Node.js ke 5 Big Benefits:

1. JavaScript Everywhere

Code
// Frontend (React) – same language
function Button() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count+1)}>{count}</button>;
}

// Backend (Node.js) – same language!
app.get('/api/count', (req, res) => {
  let count = 0;
  res.json({ count });
});

2. Non-blocking & Async

Code
// Node.js – doesn't wait!
app.get('/api/users', async (req, res) => {
  const users = await db.users.findMany(); // Non-blocking
  res.json(users); // Other requests can be processed while waiting
});

3. Fast Execution (V8 Engine)

  • Chrome V8 engine compiles JS to machine code
  • 2-3x faster than Python, Ruby

4. NPM Ecosystem

Code
npm install express mongoose dotenv jsonwebtoken bcrypt
# 2M+ packages – kuch bhi install karo!

5. Great for Real-time Apps

  • Chat apps, gaming, live tracking
  • WebSocket support

When to Use Node.js:

Best ForAvoid For
REST APIsCPU-intensive tasks (image processing)
Real-time apps (chat, gaming)Heavy machine learning
MicroservicesComplex computation
Serverless functions(Use Python/Go for those)
MERN/MEAN stack

3. How Node.js Works – Architecture (Event Loop)

Node.js

Node.js single-threaded hai lekin non-blocking।

Traditional Server (PHP, Ruby):

Code
Request 1 → [Thread 1] → Wait for DB → Response
Request 2 → [Thread 2] → Wait for DB → Response
Request 3 → [Thread 3] → Wait for DB → Response

Har request ke liye naya thread! (Memory heavy)

Node.js Server:

Code
Request 1 → Event Loop → DB Request (non-blocking)
Request 2 → Event Loop → DB Request (non-blocking)  
Request 3 → Event Loop → DB Request (non-blocking)

DB Response → Event Loop → Response

Ek thread, millions of connections!

Event Loop Visualization:

Code
   ┌───────────────────────────┐
┌─>│           timers          │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           poll            │ ← I/O operations
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘

4. Installation – Node.js and npm Setup

Step 1: Download Node.js

  • Go to nodejs.org
  • Download LTS version (Long Term Support) – Node.js 24 in 2026
  • Windows: .msi installer
  • macOS: .pkg installer
  • Linux: Package manager

Step 2: Verify Installation

Code
# Check Node.js version
node --version
# Output: v24.0.0 (or similar)

# Check npm version
npm --version
# Output: 10.x.x

Step 3: Pehla Node.js Program

Code
# Create project folder
mkdir my-first-node-app
cd my-first-node-app

# Create file
touch app.js
# or
echo "console.log('Hello Node.js!');" > app.js

# Run
node app.js
# Output: Hello Node.js!

5. Pehla Node.js Program – Hello World

Basic JavaScript in Node.js:

Code
// app.js

// Variables
const name = "Rahul";
let age = 25;

// Functions
function greet() {
console.log(`Hello, ${name}! You are ${age} years old.`);
}

greet();

// Arrays
const fruits = ["apple", "banana", "mango"];
fruits.forEach(fruit => console.log(fruit));

// Objects
const user = {
id: 1,
name: "Rahul",
email: "vivek@example.com"
};

console.log(user.name);

// Async example
setTimeout(() => {
console.log("This runs after 2 seconds!");
}, 2000);

console.log("This runs immediately!");

Run:

Code
node app.js

6. HTTP Module – Basic Server बनाएँ

Node.js built-in HTTP module se server bana sakte ho (bina kisi package ke)।

Basic HTTP Server:

Code
// server.js
const http = require('http');

// Create server
const server = http.createServer((req, res) => {
  console.log(`Request received: ${req.method} ${req.url}`);
  
  // Set response headers
  res.writeHead(200, { 'Content-Type': 'text/html' });
  
  // Send response
  res.end(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>My Node.js Server</title>
      </head>
      <body>
        <h1>Hello from Node.js!</h1>
        <p>Your first backend server is running! 🚀</p>
      </body>
    </html>
  `);
});

// Start server
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

Handle Different Routes:

Code
// server-with-routes.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'application/json');
  
  // Handle different URLs
  if (req.url === '/') {
    res.writeHead(200);
    res.end(JSON.stringify({ message: 'Welcome to Home Page!' }));
    
  } else if (req.url === '/api/users') {
    const users = [
      { id: 1, name: 'Rahul' },
      { id: 2, name: 'Priya' },
      { id: 3, name: 'Amit' }
    ];
    res.writeHead(200);
    res.end(JSON.stringify(users));
    
  } else if (req.url === '/api/products') {
    const products = [
      { id: 1, name: 'Laptop', price: 50000 },
      { id: 2, name: 'Mouse', price: 500 }
    ];
    res.writeHead(200);
    res.end(JSON.stringify(products));
    
  } else {
    res.writeHead(404);
    res.end(JSON.stringify({ error: 'Route not found' }));
  }
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Problem with HTTP Module:

  • Manual route handling – boring
  • No middleware support
  • No body parsing
  • Complex for real apps

Solution: Express.js!

7. NPM – Packages Manage Karna

NPM (Node Package Manager) – packages install aur manage karne ka tool।

Basic NPM Commands:

Code
# Initialize project (creates package.json)
npm init -y

# Install a package
npm install express

# Install dev dependency
npm install -D nodemon

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

# Uninstall package
npm uninstall express

# Update packages
npm update

# Install all dependencies (from package.json)
npm install

package.json Structure:

Code
{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "My first Node.js app",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  },
  "keywords": ["nodejs", "express", "api"],
  "author": "Rahul",
  "license": "ISC"
}

8. Express.js – Professional Server बनाएँ

Express.js Node.js ka most popular framework – APIs banane ke liye।

Installation:

Code
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
npm install -D nodemon

Basic Express Server:

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

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

// Middleware to parse JSON
app.use(express.json());

// Routes
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to Express.js Server!' });
});

app.get('/api/users', (req, res) => {
  const users = [
    { id: 1, name: 'Rahul', email: 'rahul@example.com' },
    { id: 2, name: 'Priya', email: 'priya@example.com' }
  ];
  res.json(users);
});

app.post('/api/users', (req, res) => {
  const newUser = req.body;
  console.log('New user:', newUser);
  res.status(201).json({ message: 'User created!', user: newUser });
});

app.get('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  res.json({ message: `Get user with ID: ${userId}` });
});

app.put('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  const updatedData = req.body;
  res.json({ message: `User ${userId} updated!`, data: updatedData });
});

app.delete('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  res.json({ message: `User ${userId} deleted!` });
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

package.json scripts:

Code
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  }
}

Run:

Code
npm run dev

9. REST API – CRUD Operations

Complete REST API with in-memory storage:

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

const app = express();
app.use(express.json());

const PORT = 3000;

// In-memory database
let products = [
  { id: 1, name: 'Laptop', price: 50000, inStock: true },
  { id: 2, name: 'Mouse', price: 500, inStock: true },
  { id: 3, name: 'Keyboard', price: 1500, inStock: false }
];

let nextId = 4;

// GET all products
app.get('/api/products', (req, res) => {
  res.json({
    success: true,
    count: products.length,
    data: products
  });
});

// GET single product
app.get('/api/products/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const product = products.find(p => p.id === id);
  
  if (!product) {
    return res.status(404).json({
      success: false,
      message: 'Product not found'
    });
  }
  
  res.json({
    success: true,
    data: product
  });
});

// POST create product
app.post('/api/products', (req, res) => {
  const { name, price, inStock } = req.body;
  
  // Validation
  if (!name || !price) {
    return res.status(400).json({
      success: false,
      message: 'Name and price are required'
    });
  }
  
  const newProduct = {
    id: nextId++,
    name,
    price,
    inStock: inStock !== undefined ? inStock : true
  };
  
  products.push(newProduct);
  
  res.status(201).json({
    success: true,
    data: newProduct
  });
});

// PUT update product
app.put('/api/products/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const { name, price, inStock } = req.body;
  
  const productIndex = products.findIndex(p => p.id === id);
  
  if (productIndex === -1) {
    return res.status(404).json({
      success: false,
      message: 'Product not found'
    });
  }
  
  products[productIndex] = {
    ...products[productIndex],
    name: name || products[productIndex].name,
    price: price || products[productIndex].price,
    inStock: inStock !== undefined ? inStock : products[productIndex].inStock
  };
  
  res.json({
    success: true,
    data: products[productIndex]
  });
});

// DELETE product
app.delete('/api/products/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const productIndex = products.findIndex(p => p.id === id);
  
  if (productIndex === -1) {
    return res.status(404).json({
      success: false,
      message: 'Product not found'
    });
  }
  
  products.splice(productIndex, 1);
  
  res.json({
    success: true,
    message: 'Product deleted successfully'
  });
});

// Start server
app.listen(PORT, () => {
  console.log(`🚀 Server running on http://localhost:${PORT}`);
  console.log(`📦 Products API: http://localhost:${PORT}/api/products`);
});

Testing API with curl:

Code
# GET all products
curl http://localhost:3000/api/products

# GET single product
curl http://localhost:3000/api/products/1

# POST create product
curl -X POST http://localhost:3000/api/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Monitor","price":10000,"inStock":true}'

# PUT update product
curl -X PUT http://localhost:3000/api/products/1 \
  -H "Content-Type: application/json" \
  -d '{"price":45000}'

# DELETE product
curl -X DELETE http://localhost:3000/api/products/3

10. Environment Variables – .env File

Environment variables sensitive data (API keys, database URLs) store karne ke liye।

Installation:

Code
npm install dotenv

Create .env file:

Code
# .env
PORT=5000
NODE_ENV=development
DB_URL=mongodb://localhost:27017/mydb
JWT_SECRET=my_super_secret_key_2026
API_KEY=abc123xyz

Use in server.js:

Code
// server.js
require('dotenv').config(); // Load environment variables

const express = require('express');

const app = express();
const PORT = process.env.PORT || 3000;
const NODE_ENV = process.env.NODE_ENV;

console.log(`Running in ${NODE_ENV} mode`);

app.get('/api/config', (req, res) => {
  res.json({
    nodeEnv: NODE_ENV,
    dbUrl: process.env.DB_URL,
    // Don't send secrets to client!
  });
});

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

.gitignore (don’t commit .env):

Code
# .gitignore
node_modules/
.env
.DS_Store

11. Deployment – Server Live कैसे करे

Option 1: Render (Free, Easy)

  1. Sign up at render.com
  2. Connect GitHub repository
  3. Create Web Service
  4. Set:
    • Build Command: npm install
    • Start Command: npm start
  5. Deploy!

Option 2: Vercel (Best for Node.js APIs)

Code
npm install -g vercel
vercel

Option 3: Railway (Simple)

  1. Sign up at railway.app
  2. Click “Deploy from GitHub”
  3. Select repository
  4. Done!

Option 4: DigitalOcean (VPS – Advanced)

Code
# SSH into server
ssh root@your-server-ip

# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

# Clone and run
git clone your-repo
cd your-repo
npm install
npm start

# Use PM2 for process management
npm install -g pm2
pm2 start server.js
pm2 save
pm2 startup

12. Common Mistakes + Solutions

Mistake 1: Blocking the Event Loop

Code
// ❌ Bad – blocks the event loop
app.get('/api/slow', (req, res) => {
const start = Date.now()
while (Date.now() - start < 5000) {
// Busy‑wait for ~5 seconds
}
res.json({ message: 'Done' })
})

// ✅ Good – use async operations
app.get('/api/fast', async (req, res) => {
await someAsyncOperation();
res.json({ message: 'Done' });
});

Mistake 2: Forgetting express.json() middleware

Code
// ❌ req.body will be undefined
app.post('/api/users', (req, res) => {
  console.log(req.body); // undefined!
});

// ✅ Add middleware
app.use(express.json());

Mistake 3: Not handling 404

Code
// ❌ No 404 handler – server hangs
app.get('/api/users', handler);

// ✅ Add 404 handler at the end
app.use((req, res) => {
  res.status(404).json({ error: 'Route not found' });
});

Mistake 4: Hardcoding port

Code
// ❌ Hardcoded port – can't deploy on different ports
app.listen(3000);

// ✅ Use environment variable
const PORT = process.env.PORT || 3000;
app.listen(PORT);

13. Quick Cheat Sheet

ConceptSyntax
Create serverconst app = express()
GET routeapp.get('/path', handler)
POST routeapp.post('/path', handler)
PUT routeapp.put('/path/:id', handler)
DELETE routeapp.delete('/path/:id', handler)
URL paramsreq.params.id
Query paramsreq.query.page
Request bodyreq.body (needs middleware)
Response JSONres.json(data)
Response statusres.status(201).json(data)
Middlewareapp.use(express.json())
Portconst PORT = process.env.PORT || 3000

14. FAQ

Q1: Node.js Kya Hai – simple words mein batao?
Node.js ek runtime hai jo JavaScript ko server-side run karne deta hai। Pehle JS sirf browser mein chalti thi।

Q2: Node.js single-threaded hai – ye performance issue nahi hai?
Nahi! Non-blocking I/O aur event loop ki wajah se ek thread millions of connections handle kar sakta hai।

Q3: Express.js kyun use karein?
HTTP module manual hai – routes handle karna, middleware, body parsing – sab khud likhna padta hai। Express sab kuch built-in deta hai।

Q4: npm kya hai?
Node Package Manager – packages install/manage karne ka tool। 2M+ free packages available।

Q5: nodemon kyun use karein?
Code change par server automatically restart karta है – development time save hota hai।

Q6: Environment variables (.env) kyun use karein?
Sensitive data (API keys, DB passwords) code mein hardcode nahi karna chahiye। .env file use karo aur gitignore mein daalo।

Q7: Kya Node.js CPU-intensive tasks ke liye accha hai?
Nahi – image processing, video encoding, ML ke liye Python/Go better hai। Node.js I/O-heavy apps (APIs, real-time) ke liye best hai।

Q8: Production mein server kaise run karein?
PM2 (process manager) use karo – auto-restart, clustering, logging।

Q9: Node.js version kaunsa use karein 2026 mein?
LTS version – Node.js 24। Stable, security updates milte hain।

Q10: Node.js vs Python – backend ke liye kya better hai?
APIs, real-time, microservices – Node.js। Data science, ML, compute-heavy – Python। Dono use kar sakte ho (microservices architecture)!

15. Conclusion

बहुत बढ़िया दोस्तों! आज हमने Node.js backend server Hindi को पूरी detail में समझा।

Quick Recap:

ConceptKey Takeaway
Node.jsJavaScript runtime for backend
Event LoopNon-blocking, single-threaded architecture
Express.jsMost popular framework for APIs
NPMPackage manager with 2M+ packages
REST APIGET, POST, PUT, DELETE endpoints

Mera personal experience:

जब मैंने पहली बार Node.js सीखा, तो मुझे event loop samajhna thoda mushkil laga। Lekin ek baar async/await samajh aaya toh backend development bohot easy lagne laga। Express.js se toh API banane mein minutes lagte hain!

Tum bhi ye steps follow karo:

  1. ✅ Node.js install karo
  2. ✅ Pehla HTTP server banao
  3. ✅ Express.js se REST API banao
  4. ✅ .env file setup karo
  5. ✅ Render.com pe deploy karo

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

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

  1. तुम्हें Node.js easy laga ya complex?
  2. क्या तुमने Express.js try kiya?
  3. अगला topic क्या चाहिए? (Express.js Deep Dive? MongoDB? JWT Authentication?)

The Easy Master पर बने रहो। Happy Backend Coding! 🚀💻


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 *