Node.js Introduction
BeginnerImagine you have a toy robot: This robot can only move when you wind it up (like websites that only work in browsers). But what if you want your robot to work anywhere - in your room, garden, or park?
Node.js is like giving your robot batteries! It lets JavaScript (the programming language) run anywhere on your computer, not just in web browsers. Before Node.js, JavaScript was like a fish that could only live in water (browsers). Node.js gave it legs to walk on land (servers and computers)!
Real-world example: Think of Netflix. When you click "Play", Node.js helps send the video from their computers to yours super fast. It's like a super-efficient delivery person who can handle thousands of deliveries at once!
Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome's V8 JavaScript engine. It enables JavaScript code execution outside of web browsers, primarily used for building scalable network applications and server-side programming. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient for data-intensive real-time applications.
- JavaScript Everywhere: Write both frontend and backend code in the same language
- Built on V8 Engine: Uses Google Chrome's super-fast JavaScript engine
- Non-blocking I/O: Can handle many tasks at once without waiting
- NPM Ecosystem: Access to over 1 million free packages/libraries
- Single-threaded: Uses one main thread but handles multiple operations efficiently
- Event-driven: Responds to events (like user clicks, file reads) as they happen
- Cross-platform: Works on Windows, Mac, Linux, and more
Answer: Node.js ek JavaScript runtime environment hai jo Chrome ke V8 engine par based hai. Isko use karne ke main reasons hain:
- JavaScript har jagah: Frontend aur backend dono mein same language use kar sakte hain
- Fast performance: V8 engine bahut fast hai, code ko machine code mein compile karta hai
- Non-blocking: Ek time pe bahut saare requests handle kar sakta hai bina wait kiye
- NPM: Lakhs ready-made packages milte hain jo development fast banate hain
- Real-time apps: Chat apps, gaming, live streaming ke liye perfect hai
Example: Agar aapko ek chat application banana hai jisme 10,000 users simultaneously chat kar rahe hain, to Node.js perfect choice hai kyunki ye efficiently handle kar sakta hai.
Answer: Main differences:
- Environment: Browser mein JavaScript sirf web pages ke andar run hota hai. Node.js mein aap apne computer par kahin bhi run kar sakte ho
- DOM Access: Browser mein document, window objects milte hain. Node.js mein ye nahi milte kyunki wahan HTML page nahi hota
- File System: Browser mein aap directly files read/write nahi kar sakte security reasons se. Node.js mein full file system access hai
- Modules: Browser mein ES6 modules use hote hain. Node.js mein CommonJS (require/module.exports) bhi use hota hai
- Global Objects: Browser mein 'window' global object hai. Node.js mein 'global' object hai
Simple analogy: Browser JavaScript ek aquarium mein fish ki tarah hai - safe but limited. Node.js ocean mein fish ki tarah hai - complete freedom!
Answer: V8 Engine Google ka open-source JavaScript engine hai jo C++ mein likha gaya hai.
Kaise kaam karta hai:
- Compilation: JavaScript code ko directly machine code mein convert karta hai (JIT - Just In Time compilation)
- Optimization: Code ko analyze karke optimize karta hai runtime pe
- Memory Management: Automatic garbage collection provide karta hai
- Fast Execution: Interpreted languages se kaafi fast hai
Node.js mein role: Node.js ne V8 engine ko liya aur uske saath additional features add kiye jaise file system access, networking capabilities, etc. Ye combination Node.js ko bahut powerful banata hai.
Real example: Jaise car mein engine hota hai jo power deta hai, waise hi V8 engine Node.js ko power deta hai JavaScript code execute karne ke liye.
Event Loop & Architecture
IntermediateImagine a restaurant with one waiter: The waiter (Event Loop) doesn't wait for one table's food to be cooked before taking another table's order. He takes orders from all tables, gives them to the kitchen, and when food is ready, he delivers it!
This is exactly how Node.js works! It doesn't wait for slow operations (like reading files or database queries) to finish. It starts them, moves to the next task, and comes back when they're done.
Real-world example: When you order food on Swiggy, the app doesn't freeze waiting for restaurant confirmation. It lets you browse other restaurants while processing your order in the background!
Event Loop is the core mechanism that enables Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. It continuously monitors the call stack and callback queue, executing callbacks when the call stack is empty. The architecture consists of phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks, each handling specific types of operations in a cyclical manner.
- Single-threaded: One main thread handles all JavaScript execution
- Non-blocking: Doesn't wait for slow operations to complete
- Event-driven: Responds to events using callbacks
- Phases: Event loop has 6 phases that execute in order
- Callback Queue: Stores callbacks waiting to be executed
- Libuv: C library that provides the event loop and async I/O
- Microtasks: Promises and process.nextTick have higher priority
Answer: Event Loop ek continuous cycle hai jo 6 phases mein kaam karta hai:
- Timers Phase: setTimeout aur setInterval ke callbacks execute hote hain
- Pending Callbacks: Previous cycle ke pending I/O callbacks execute hote hain
- Idle/Prepare: Internal use ke liye (developers ko concern nahi)
- Poll Phase: New I/O events retrieve karta hai, I/O callbacks execute karta hai
- Check Phase: setImmediate callbacks execute hote hain
- Close Callbacks: socket.on('close') jaise callbacks execute hote hain
Important: Har phase ke beech mein microtasks (Promises, process.nextTick) execute hote hain - inki priority sabse zyada hai!
Simple analogy: Jaise traffic signal ka cycle - red, yellow, green - waise hi event loop apne phases mein cycle karta rehta hai.
Answer: Ye Node.js ka sabse interesting part hai!
Main thread single hai but:
- Non-blocking I/O: Jab file read ya database query hoti hai, Node.js wait nahi karta. Wo operation ko background mein daal deta hai aur next request handle karne lagta hai
- Libuv Thread Pool: Heavy operations (file I/O, DNS lookup, crypto) ke liye 4 background threads use hote hain by default
- Event Loop: Jab background operation complete hota hai, callback queue mein aata hai aur event loop use execute karta hai
- Async Nature: Sab kuch asynchronous hai, isliye ek request dusre ko block nahi karti
Example: Agar 1000 users simultaneously file download kar rahe hain, to Node.js sabko start kar deta hai. Jaise hi kisi ka download complete hota hai, usko response bhej deta hai. Kisi ko wait nahi karna padta!
Limitation: CPU-intensive tasks (heavy calculations) ke liye Node.js best nahi hai kyunki wo main thread ko block kar dete hain.
Asynchronous Programming
BeginnerImagine you're cooking: You put rice on the stove (starts cooking), while it cooks, you chop vegetables, then you start the curry. You don't stand and stare at the rice until it's done - that would be synchronous (blocking)!
Asynchronous is multitasking! You start multiple tasks and handle them as they complete. In programming, this means your code doesn't wait for slow operations (file reading, API calls) to finish before moving to the next line.
Real-world example: When you send a WhatsApp message, you can immediately type another message. You don't wait for the first one to be delivered (that's async!). If you had to wait, that would be synchronous.
Asynchronous Programming is a programming paradigm that allows code execution to continue without waiting for long-running operations to complete. In Node.js, asynchronous operations are handled through callbacks, Promises, and async/await syntax, enabling non-blocking I/O operations and efficient resource utilization in single-threaded environments.
- Non-blocking: Code continues executing without waiting
- Callbacks: Functions passed as arguments, executed when operation completes
- Promises: Objects representing eventual completion/failure of async operation
- Async/Await: Syntactic sugar making async code look synchronous
- Error Handling: Must handle errors differently than sync code
- Callback Hell: Nested callbacks can become hard to read (pyramid of doom)
Answer: Ye teen tarike hain asynchronous code likhne ke:
1. CALLBACKS:
- Sabse purana tarika
- Function ko argument mein pass karte hain
- Problem: Callback hell (nested callbacks bahut complex ho jate hain)
- Error handling mushkil hai
2. PROMISES:
- Callbacks se better, cleaner code
- .then() aur .catch() use karte hain
- Chaining possible hai
- Error handling easier hai
3. ASYNC/AWAIT:
- Sabse modern aur readable
- Synchronous code jaisa dikhta hai but asynchronous hai
- try-catch se error handling
- Debugging easy hai
Kab kya use karein: New projects mein hamesha async/await use karo. Purane code mein callbacks mil sakte hain. Promises middle ground hai.
Answer:
Promise.all():
- Multiple promises ko parallel run karta hai
- Jab SAARE promises resolve ho jaye tab result deta hai
- Agar ek bhi promise reject ho jaye, to pura reject ho jata hai
- Result array mein milta hai same order mein
Promise.race():
- Multiple promises ko parallel run karta hai
- Jo PEHLA promise complete ho (resolve ya reject), uska result deta hai
- Baaki promises ignore ho jate hain
- Timeout implement karne ke liye useful
Use case: Promise.all() jab sabka result chahiye (jaise 3 APIs se data fetch karna). Promise.race() jab fastest result chahiye (jaise timeout lagana).
Error Handling in Async Code
IntermediateImagine you're ordering food online: Many things can go wrong - restaurant closed, delivery person unavailable, payment failed. Good apps show you proper error messages instead of just crashing!
In async code, errors happen differently: Since code doesn't wait, errors can occur later. You need special ways to catch them - like having a safety net for a trapeze artist!
Real-world example: When you try to upload a photo on Instagram and internet disconnects, the app catches the error and shows "Upload failed. Retry?" instead of crashing.
Asynchronous Error Handling involves managing errors that occur during non-blocking operations. In Node.js, this includes callback error-first pattern, Promise rejection handling with .catch() or try-catch with async/await, and global error handlers for unhandled rejections and uncaught exceptions.
Answer: Jab Promise reject hota hai aur uske liye .catch() ya try-catch nahi hai, to wo unhandled rejection ban jata hai.
Problem:
- Application crash ho sakta hai
- Silent failures ho sakti hain (error dikhta nahi)
- Debugging mushkil ho jati hai
- Production mein serious issues create kar sakta hai
Solution:
Best Practice: Har Promise ke saath error handling honi chahiye. Global handler sirf backup ke liye use karo.
Node.js Modules System
BeginnerImagine building with LEGO blocks: Instead of creating one giant piece, you make small blocks that fit together. Each block has a specific purpose - wheels, windows, doors. You can reuse these blocks in different projects!
Modules are like LEGO blocks for code! Instead of writing all code in one file, you split it into smaller files (modules). Each module does one thing well. You can use these modules in different projects.
Real-world example: Think of a smartphone - camera module, battery module, screen module. Each works independently but together they make a phone. If camera breaks, you replace just that module!
Node.js Modules are reusable blocks of code whose existence does not impact other code unless explicitly imported. Node.js supports two module systems: CommonJS (require/module.exports) and ES Modules (import/export). Modules provide encapsulation, reusability, and maintainability by organizing code into logical units with defined interfaces.
- Three Types: Core modules (built-in), Local modules (your files), Third-party modules (npm packages)
- CommonJS: Uses require() and module.exports (traditional Node.js way)
- ES Modules: Uses import/export (modern JavaScript standard)
- Encapsulation: Variables in modules are private by default
- Caching: Modules are cached after first load for performance
- NPM: Node Package Manager - world's largest software registry
Answer:
COMMONJS (require/module.exports):
- Node.js ka original module system
- Synchronous loading - modules load hone tak wait karta hai
- Runtime pe modules load hote hain
- Dynamic imports possible - conditional require() kar sakte ho
- File extension: .js
- Default in Node.js
ES MODULES (import/export):
- JavaScript ka official standard (ECMAScript)
- Asynchronous loading - non-blocking
- Compile time pe analyze hote hain (tree-shaking possible)
- Static imports - top level pe hone chahiye
- File extension: .mjs ya package.json mein "type": "module"
- Browser aur Node.js dono mein same syntax
Kaunsa better hai?
- New projects: ES Modules use karo - future standard hai
- Old projects: CommonJS already use ho raha to continue karo
- Libraries: Dono support karo for maximum compatibility
Practical tip: Modern Node.js (v12+) dono support karta hai. Tum choose kar sakte ho based on project needs.
Answer:
NPM (Node Package Manager):
- World's largest software registry - 2 million+ packages
- Command-line tool jo Node.js ke saath aata hai
- Packages install, update, remove karne ke liye
- Dependencies manage karta hai automatically
package.json - Project ka blueprint:
- Metadata: Project name, version, description, author
- Dependencies: Konse packages chahiye production mein
- DevDependencies: Development ke liye packages (testing, linting)
- Scripts: Custom commands (npm start, npm test)
- Entry Point: Main file konsi hai
Kyun important hai: Agar tum project share karo, dusra person sirf `npm install` run karega aur saare dependencies automatically install ho jayenge!
Answer: Module caching ek optimization technique hai jo Node.js use karta hai.
Kaise kaam karta hai:
- Jab pehli baar module require karte ho, Node.js use load aur execute karta hai
- Result ko cache mein store kar leta hai
- Agli baar same module require karo to cache se return kar deta hai
- Module ka code dobara execute nahi hota
Benefits:
- Performance improvement - fast loading
- Memory efficient - ek hi copy memory mein
- Singleton pattern automatically
Cache clear karna:
Core Modules Overview
BeginnerImagine a Swiss Army knife: It comes with many built-in tools - knife, scissors, screwdriver, bottle opener. You don't need to buy these separately!
Node.js Core Modules are like that! They're built-in tools that come with Node.js. You don't need to install them - just require and use! Each module does specific tasks like reading files, creating servers, working with paths, etc.
Real-world example: Your smartphone has built-in apps - Camera, Calculator, Clock. You don't download these, they come pre-installed. Core modules are pre-installed tools in Node.js!
Core Modules are built-in modules compiled into the Node.js binary, providing essential functionality for common programming tasks. They include modules for file system operations (fs), networking (http, https, net), path manipulation (path), operating system interaction (os), cryptography (crypto), streams, buffers, and more. These modules are optimized, well-tested, and maintained by the Node.js core team.
- No Installation: Built-in, just require them
- Optimized: Written in C/C++ for performance
- Stable: Well-tested and maintained
- Essential: Cover most common programming needs
- Documentation: Official Node.js docs have complete reference
File System (fs) Module
BeginnerImagine a filing cabinet: You can open it, read documents, add new papers, delete old ones, organize folders. The fs module lets your code do the same with computer files!
fs module is your file manager! It can read files (like opening a book), write files (like writing in a notebook), delete files (like throwing paper in trash), create folders, and much more.
Real-world example: When you save a Word document, the application uses file system operations to write data to your hard drive. Node.js fs module gives you the same power!
Answer:
fs.readFile() - ASYNCHRONOUS:
- Non-blocking - file read hone tak code aage badhta rehta hai
- Callback function use karta hai
- Other operations block nahi hote
- Production code ke liye recommended
- Multiple files parallel mein read kar sakte ho
fs.readFileSync() - SYNCHRONOUS:
- Blocking - file read hone tak wait karta hai
- Direct value return karta hai
- Baaki sab operations ruk jate hain
- Sirf simple scripts ya startup code mein use karo
- Server code mein AVOID karo
Kaunsa use karein:
- Production/Server: Hamesha async (readFile) use karo
- Simple scripts: Sync use kar sakte ho
- Config files: Startup pe sync OK hai
- Best: Promises/async-await use karo (fs.promises.readFile)
Answer: Streams data ko chunks (small pieces) mein process karne ka tarika hai.
Simple analogy: Imagine ek bucket se dusre bucket mein paani transfer karna hai:
- Without streams: Pura bucket uthao, le jao, dalo (heavy, slow)
- With streams: Pipe laga do, paani flow hota rahega (efficient, continuous)
Kyun use karein:
- Memory efficient: Puri file memory mein load nahi hoti, chunks process hote hain
- Fast: Processing start ho jati hai pehle chunk se hi
- Large files: GB size ki files bhi handle kar sakte ho
- Real-time: Data aate hi process hota hai
Types of streams:
- Readable: Data read karne ke liye (fs.createReadStream)
- Writable: Data write karne ke liye (fs.createWriteStream)
- Duplex: Read aur write dono (TCP sockets)
- Transform: Data modify karte hue pass karna (compression)
HTTP & HTTPS Modules
BeginnerImagine a restaurant: Customers (clients) place orders (requests), waiters take orders to kitchen (server), kitchen prepares food, waiters bring food back (response). HTTP module helps you create this restaurant in code!
HTTP module creates web servers! It listens for requests from browsers/apps, processes them, and sends back responses. HTTPS is the secure version - like having security guards at your restaurant!
Real-world example: When you visit google.com, your browser sends an HTTP request. Google's servers (built with tools like HTTP module) receive it and send back the webpage!
Hello World!
'); res.end(); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); // ========== ROUTING (Different URLs) ========== const serverWithRouting = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Home Page
'); } else if (req.url === '/about') { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('About Page
'); } else if (req.url === '/api/users') { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({ users: ['John', 'Jane'] })); } else { res.writeHead(404, {'Content-Type': 'text/html'}); res.end('404 - Page Not Found
'); } }); serverWithRouting.listen(3000); // ========== HTTPS SERVER (Secure) ========== const options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('certificate.pem') }; const httpsServer = https.createServer(options, (req, res) => { res.writeHead(200); res.end('Secure connection!'); }); httpsServer.listen(443); // ========== MAKING HTTP REQUESTS ========== // GET request http.get('http://api.example.com/data', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log(JSON.parse(data)); }); }); // POST request const postData = JSON.stringify({ name: 'John' }); const options = { hostname: 'api.example.com', port: 80, path: '/users', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; const req = http.request(options, (res) => { console.log(`Status: ${res.statusCode}`); res.on('data', (chunk) => { console.log(chunk.toString()); }); }); req.write(postData); req.end();Answer:
HTTP (HyperText Transfer Protocol):
- Plain text mein data transfer hota hai
- Koi bhi beech mein data dekh sakta hai (man-in-the-middle attack)
- Port 80 use karta hai
- Fast hai kyunki encryption nahi hai
- Non-sensitive data ke liye OK
HTTPS (HTTP Secure):
- Encrypted data transfer - SSL/TLS use karta hai
- Data scrambled hai, koi beech mein nahi dekh sakta
- Port 443 use karta hai
- Thoda slow (encryption overhead)
- Passwords, payments, personal info ke liye MUST
- Green padlock browser mein dikhta hai
Kaise secure hai:
- Encryption: Data ko code mein convert karta hai
- Authentication: Verify karta hai ki server genuine hai
- Integrity: Data tamper nahi ho sakta beech mein
Example: Jab tum bank website pe login karte ho, HTTPS ensure karta hai ki tumhara password encrypted form mein jaye. HTTP use karo to password plain text mein jayega - bahut dangerous!
Modern web: Google ab HTTPS ko ranking factor banata hai. Sabhi websites ko HTTPS use karna chahiye.
Answer:
req (Request Object) - Client se aane wali information:
- req.url: Konsa URL request kiya (e.g., '/about', '/api/users')
- req.method: HTTP method (GET, POST, PUT, DELETE)
- req.headers: Request headers (cookies, auth tokens, content-type)
- req.body: POST/PUT data (form data, JSON) - middleware chahiye
- req.query: URL query parameters (?name=John&age=25)
- req.params: Route parameters (/users/:id)
res (Response Object) - Client ko bhejne wali information:
- res.writeHead(): Status code aur headers set karta hai
- res.write(): Response body mein data likhta hai
- res.end(): Response complete karta hai aur send karta hai
- res.statusCode: HTTP status code set karta hai (200, 404, 500)
- res.setHeader(): Individual header set karta hai
Common status codes:
```html processes them, and sends back responses. HTTPS is the secure version - like having security guards at your restaurant!Real-world example: When you visit google.com, your browser sends an HTTP request. Google's servers (built with tools like HTTP module) receive it and send back the webpage!
Hello World!
'); res.end(); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); // ========== ROUTING (Different URLs) ========== const serverWithRouting = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Home Page
'); } else if (req.url === '/about') { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('About Page
'); } else if (req.url === '/api/users') { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({ users: ['John', 'Jane'] })); } else { res.writeHead(404, {'Content-Type': 'text/html'}); res.end('404 - Page Not Found
'); } }); serverWithRouting.listen(3000); // ========== HTTPS SERVER (Secure) ========== const options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('certificate.pem') }; const httpsServer = https.createServer(options, (req, res) => { res.writeHead(200); res.end('Secure connection!'); }); httpsServer.listen(443); // ========== MAKING HTTP REQUESTS ========== // GET request http.get('http://api.example.com/data', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log(JSON.parse(data)); }); }); // POST request const postData = JSON.stringify({ name: 'John' }); const options = { hostname: 'api.example.com', port: 80, path: '/users', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; const req = http.request(options, (res) => { console.log(`Status: ${res.statusCode}`); res.on('data', (chunk) => { console.log(chunk.toString()); }); }); req.write(postData); req.end();Answer:
HTTP (HyperText Transfer Protocol):
- Plain text mein data transfer hota hai
- Koi bhi beech mein data dekh sakta hai (man-in-the-middle attack)
- Port 80 use karta hai
- Fast hai kyunki encryption nahi hai
- Non-sensitive data ke liye OK
HTTPS (HTTP Secure):
- Encrypted data transfer - SSL/TLS use karta hai
- Data scrambled hai, koi beech mein nahi dekh sakta
- Port 443 use karta hai
- Thoda slow (encryption overhead)
- Passwords, payments, personal info ke liye MUST
- Green padlock browser mein dikhta hai
Kaise secure hai:
- Encryption: Data ko code mein convert karta hai
- Authentication: Verify karta hai ki server genuine hai
- Integrity: Data tamper nahi ho sakta beech mein
Example: Jab tum bank website pe login karte ho, HTTPS ensure karta hai ki tumhara password encrypted form mein jaye. HTTP use karo to password plain text mein jayega - bahut dangerous!
Modern web: Google ab HTTPS ko ranking factor banata hai. Sabhi websites ko HTTPS use karna chahiye.
Answer:
req (Request Object) - Client se aane wali information:
- req.url: Konsa URL request kiya (e.g., '/about', '/api/users')
- req.method: HTTP method (GET, POST, PUT, DELETE)
- req.headers: Request headers (cookies, auth tokens, content-type)
- req.body: POST/PUT data (form data, JSON) - middleware chahiye
- req.query: URL query parameters (?name=John&age=25)
- req.params: Route parameters (/users/:id)
res (Response Object) - Client ko bhejne wali information:
- res.writeHead(): Status code aur headers set karta hai
- res.write(): Response body mein data likhta hai
- res.end(): Response complete karta hai aur send karta hai
- res.statusCode: HTTP status code set karta hai (200, 404, 500)
- res.setHeader(): Individual header set karta hai
Common status codes:
- 200: OK - Success
- 201: Created - Resource created successfully
- 400: Bad Request - Invalid data
- 401: Unauthorized - Login required
- 404: Not Found - Resource doesn't exist
- 500: Internal Server Error - Server crash
Modern JavaScript (ES6+) Features
IntermediateImagine upgrading from a bicycle to a sports car: Old JavaScript (ES5) was like a bicycle - it worked, but was slow and limited. Modern JavaScript (ES6+) is like a sports car - faster, more features, easier to drive!
ES6+ brought superpowers to JavaScript! Arrow functions make code shorter, destructuring unpacks data easily, template literals make strings better, and async/await makes asynchronous code readable.
- Arrow Functions: Shorter syntax, lexical 'this' binding
- Destructuring: Extract values from arrays/objects easily
- Template Literals: String interpolation with backticks
- Spread/Rest: ... operator for arrays and objects
- Let/Const: Block-scoped variables, const for constants
Express.js Framework
IntermediateImagine building a house: You could make every brick yourself (plain Node.js), or use pre-made materials and tools (Express.js). Express gives you ready-made tools to build web servers faster!
Express.js is like a power tool for Node.js! It makes creating web servers, handling routes, managing requests super easy. Instead of writing 100 lines of code, you write 10 lines!
- Minimalist Framework: Fast, unopinionated web framework
- Middleware: Functions that process requests before routes
- Routing: Easy URL pattern matching
- REST APIs: Perfect for building RESTful services
Answer: Middleware functions hain jo request aur response ke beech mein execute hote hain. Ye request/response modify kar sakte hain ya next middleware ko call kar sakte hain using next().
Use cases: Authentication, Logging, Body parsing, CORS, Error handling
MongoDB with Node.js
IntermediateImagine a digital filing cabinet: Instead of paper files, you store data as JSON-like documents. MongoDB is like a super-smart filing cabinet that can find, sort, and organize millions of documents instantly!
MongoDB is a NoSQL database! Unlike traditional databases with tables, MongoDB stores flexible JSON-like documents. Perfect for modern applications!
- Document-based: Stores data as BSON documents
- Flexible Schema: No fixed structure
- Mongoose: ODM library for MongoDB
- CRUD Operations: Create, Read, Update, Delete
SQL: Structured data, fixed schema, tables/rows, ACID properties, vertical scaling
NoSQL: Flexible data, dynamic schema, documents, eventual consistency, horizontal scaling
Use SQL for: Banking, finance (strict structure). NoSQL for: Social media, real-time apps (flexible, scalable)
WebSockets & Real-time Communication
AdvancedImagine a phone call vs sending letters: HTTP is like sending letters - you send, wait for reply. WebSocket is like a phone call - continuous two-way conversation!
WebSockets enable real-time communication! Server can push data to client instantly. Perfect for chat apps, live updates, gaming!
Testing with Jest
IntermediateImagine testing a car before selling: You check brakes, engine, lights. Code testing is the same - verify everything works before deployment!
Testing catches bugs early! Write tests to automatically verify your code works. If something breaks, tests fail immediately!
Deployment & Production
AdvancedImagine opening a restaurant: You test recipes at home (development), then open to public (production). Deployment is moving your app from your computer to the internet!
Production means real users! Your app needs to be secure, fast, and always available. Use proper hosting, environment variables, and monitoring!
- Environment Variables: Store secrets safely (.env files)
- PM2: Process manager, auto-restart on crash
- HTTPS: Always use SSL certificates
- Logging: Track errors and monitor performance
- Platforms: Heroku, AWS, Vercel, DigitalOcean
Performance Optimization
AdvancedImagine a highway: One lane = slow traffic. Multiple lanes = fast traffic. Clustering creates multiple lanes for your Node.js app!
Optimization makes apps faster! Use caching, compression, clustering, and efficient code. Users love fast apps!
- Clustering: Use all CPU cores, handle more requests
- Caching: Store frequently used data (Redis)
- Compression: Gzip responses to reduce bandwidth
- Database Indexing: Speed up queries dramatically
- Load Balancing: Distribute traffic across servers
Microservices Architecture
AdvancedImagine a restaurant: Monolith = one person does everything (slow!). Microservices = chef cooks, waiter serves, cashier handles payment (efficient!)
Microservices break apps into small services! Each service does one thing well. They communicate via APIs. Easy to scale and maintain!
- Independent Services: Each can be deployed separately
- API Gateway: Single entry point for all services
- Service Discovery: Services find each other dynamically
- Docker: Containerize services for consistency
- Kubernetes: Orchestrate and manage containers