🚀 Node.js Complete Study Guide

Interactive Learning Resource for Beginners to Advanced

Node.js Introduction

Beginner
🎯 Simple Explanation

Imagine 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!

📖 Technical Definition

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.

⭐ Key Points to Remember
  • 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
Simple Node.js Example
// Your first Node.js program console.log("Hello from Node.js!"); // Node.js can read files const fs = require('fs'); fs.readFile('myfile.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
💼 Interview Questions (Hinglish)
Node.js kya hai aur isko kyun use karte hain?

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.

Node.js aur browser JavaScript mein kya difference 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!

V8 Engine kya hai aur Node.js isme kaise use hota hai?

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

Intermediate
🎯 Simple Explanation

Imagine 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!

📖 Technical Definition

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.

⭐ Key Points to Remember
  • 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
Event Loop Example
console.log('1: Start'); setTimeout(() => { console.log('2: Timeout callback'); }, 0); Promise.resolve().then(() => { console.log('3: Promise callback'); }); console.log('4: End'); // Output order: // 1: Start // 4: End // 3: Promise callback (microtask - higher priority) // 2: Timeout callback (macrotask)
💼 Interview Questions (Hinglish)
Event Loop kaise kaam karta hai? Step by step explain karo.

Answer: Event Loop ek continuous cycle hai jo 6 phases mein kaam karta hai:

  1. Timers Phase: setTimeout aur setInterval ke callbacks execute hote hain
  2. Pending Callbacks: Previous cycle ke pending I/O callbacks execute hote hain
  3. Idle/Prepare: Internal use ke liye (developers ko concern nahi)
  4. Poll Phase: New I/O events retrieve karta hai, I/O callbacks execute karta hai
  5. Check Phase: setImmediate callbacks execute hote hain
  6. 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.

Node.js single-threaded hai to multiple requests kaise handle karta 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

Beginner
🎯 Simple Explanation

Imagine 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.

📖 Technical Definition

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.

⭐ Key Points to Remember
  • 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)
Three Ways to Handle Async
// 1. CALLBACKS (Old way) fs.readFile('file.txt', 'utf8', (err, data) => { if (err) console.error(err); else console.log(data); }); // 2. PROMISES (Better) fs.promises.readFile('file.txt', 'utf8') .then(data => console.log(data)) .catch(err => console.error(err)); // 3. ASYNC/AWAIT (Best - Modern way) async function readMyFile() { try { const data = await fs.promises.readFile('file.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); } }
💼 Interview Questions (Hinglish)
Callback, Promise aur Async/Await mein kya difference hai? Kab kaunsa use karein?

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.

Promise.all() aur Promise.race() mein kya difference 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
const p1 = Promise.resolve(3); const p2 = Promise.resolve(42); const p3 = Promise.resolve("foo"); Promise.all([p1, p2, p3]).then(values => { console.log(values); // [3, 42, "foo"] });

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

Intermediate
🎯 Simple Explanation

Imagine 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.

📖 Technical Definition

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.

Error Handling Patterns
// 1. CALLBACK ERROR-FIRST PATTERN fs.readFile('file.txt', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log(data); }); // 2. PROMISE ERROR HANDLING fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('API Error:', error)); // 3. ASYNC/AWAIT WITH TRY-CATCH async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error.message); } } // 4. GLOBAL ERROR HANDLERS process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection:', reason); }); process.on('uncaughtException', (error) => { console.error('Uncaught Exception:', error); process.exit(1); // Exit gracefully });
💼 Interview Questions (Hinglish)
Unhandled Promise Rejection kya hai aur isko kaise handle karein?

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:

// 1. Always use .catch() myPromise() .then(result => console.log(result)) .catch(err => console.error(err)); // 2. Use try-catch with async/await async function myFunction() { try { await myPromise(); } catch (err) { console.error(err); } } // 3. Global handler (last resort) process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise); console.error('Reason:', reason); // Log to error tracking service });

Best Practice: Har Promise ke saath error handling honi chahiye. Global handler sirf backup ke liye use karo.

Node.js Modules System

Beginner
🎯 Simple Explanation

Imagine 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!

📖 Technical Definition

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.

⭐ Key Points to Remember
  • 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
Module Examples
// ========== COMMONJS (Traditional) ========== // math.js - Creating a module function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } module.exports = { add, subtract }; // app.js - Using the module const math = require('./math'); console.log(math.add(5, 3)); // 8 // ========== ES MODULES (Modern) ========== // math.mjs - Creating a module export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; } // app.mjs - Using the module import { add, subtract } from './math.mjs'; console.log(add(5, 3)); // 8 // ========== CORE MODULES ========== const fs = require('fs'); // File System const http = require('http'); // HTTP Server const path = require('path'); // Path utilities // ========== NPM MODULES ========== const express = require('express'); // Web framework const axios = require('axios'); // HTTP client
💼 Interview Questions (Hinglish)
CommonJS aur ES Modules mein kya difference hai? Kaunsa better hai?

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.

NPM kya hai aur package.json file ka kya role hai?

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
{ "name": "my-app", "version": "1.0.0", "description": "My awesome app", "main": "index.js", "scripts": { "start": "node index.js", "test": "jest", "dev": "nodemon index.js" }, "dependencies": { "express": "^4.18.0", "mongoose": "^6.0.0" }, "devDependencies": { "nodemon": "^2.0.0", "jest": "^27.0.0" } }

Kyun important hai: Agar tum project share karo, dusra person sirf `npm install` run karega aur saare dependencies automatically install ho jayenge!

Module caching kya hai aur kaise kaam karta hai?

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
// counter.js let count = 0; module.exports = { increment: () => ++count, getCount: () => count }; // app.js const counter1 = require('./counter'); const counter2 = require('./counter'); counter1.increment(); // count = 1 console.log(counter2.getCount()); // 1 (same instance!) // Both counter1 and counter2 point to SAME cached module console.log(counter1 === counter2); // true

Benefits:

  • Performance improvement - fast loading
  • Memory efficient - ek hi copy memory mein
  • Singleton pattern automatically

Cache clear karna:

// Cache se module delete karna delete require.cache[require.resolve('./counter')]; // Ab dobara require karne pe fresh load hoga const freshCounter = require('./counter');

Core Modules Overview

Beginner
🎯 Simple Explanation

Imagine 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!

📖 Technical Definition

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.

⭐ Key Points to Remember
  • 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
Common Core Modules
// ========== FILE SYSTEM (fs) ========== const fs = require('fs'); // Read file fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); // Write file fs.writeFile('output.txt', 'Hello World!', (err) => { if (err) throw err; console.log('File written!'); }); // ========== HTTP MODULE ========== const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World!'); }); server.listen(3000, () => { console.log('Server running on port 3000'); }); // ========== PATH MODULE ========== const path = require('path'); console.log(path.join('/users', 'john', 'documents')); // /users/john/documents console.log(path.extname('file.txt')); // .txt // ========== OS MODULE ========== const os = require('os'); console.log(os.platform()); // win32, darwin, linux console.log(os.cpus().length); // Number of CPU cores console.log(os.freemem()); // Free memory in bytes // ========== EVENTS MODULE ========== const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('Event occurred!'); }); myEmitter.emit('event');

File System (fs) Module

Beginner
🎯 Simple Explanation

Imagine 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!

File System Operations
const fs = require('fs'); const fsPromises = require('fs').promises; // ========== READING FILES ========== // Async (callback) fs.readFile('input.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); // Sync (blocking) const data = fs.readFileSync('input.txt', 'utf8'); console.log(data); // Promise-based (modern) async function readFile() { try { const data = await fsPromises.readFile('input.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); } } // ========== WRITING FILES ========== // Write (overwrites existing) fs.writeFile('output.txt', 'Hello World!', (err) => { if (err) throw err; console.log('File written!'); }); // Append (adds to existing) fs.appendFile('log.txt', 'New log entry\n', (err) => { if (err) throw err; console.log('Log appended!'); }); // ========== FILE/DIRECTORY OPERATIONS ========== // Check if file exists fs.access('file.txt', fs.constants.F_OK, (err) => { console.log(err ? 'File does not exist' : 'File exists'); }); // Delete file fs.unlink('oldfile.txt', (err) => { if (err) throw err; console.log('File deleted!'); }); // Create directory fs.mkdir('newFolder', { recursive: true }, (err) => { if (err) throw err; console.log('Directory created!'); }); // Read directory contents fs.readdir('./', (err, files) => { if (err) throw err; console.log('Files:', files); }); // Get file info fs.stat('file.txt', (err, stats) => { if (err) throw err; console.log('Size:', stats.size); console.log('Is file:', stats.isFile()); console.log('Is directory:', stats.isDirectory()); }); // ========== STREAMS (for large files) ========== // Read stream const readStream = fs.createReadStream('large-file.txt', 'utf8'); readStream.on('data', (chunk) => { console.log('Chunk:', chunk); }); // Write stream const writeStream = fs.createWriteStream('output.txt'); writeStream.write('Line 1\n'); writeStream.write('Line 2\n'); writeStream.end();
💼 Interview Questions (Hinglish)
fs.readFile() aur fs.readFileSync() mein kya difference hai? Kaunsa use karna chahiye?

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.readFile('file.txt', 'utf8', (err, data) => { console.log('File content:', data); }); console.log('This runs immediately!'); // Output order: // "This runs immediately!" // "File content: ..."

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
const data = fs.readFileSync('file.txt', 'utf8'); console.log('File content:', data); console.log('This runs after file is read'); // Output order: // "File content: ..." // "This runs after file is read"

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)
Streams kya hain aur large files ke liye kyun use karte hain?

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
// WITHOUT STREAMS (Bad for large files) fs.readFile('large-video.mp4', (err, data) => { // Puri file memory mein load hogi (may crash!) res.send(data); }); // WITH STREAMS (Good for large files) const readStream = fs.createReadStream('large-video.mp4'); readStream.pipe(res); // Chunks mein send hoga // EXAMPLE: Copy large file const readStream = fs.createReadStream('source.txt'); const writeStream = fs.createWriteStream('destination.txt'); readStream.pipe(writeStream); // With progress tracking readStream.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes`); }); readStream.on('end', () => { console.log('File copy complete!'); });

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

Beginner
🎯 Simple Explanation

Imagine 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!

Creating HTTP Server
const http = require('http'); const https = require('https'); const fs = require('fs'); // ========== BASIC HTTP SERVER ========== const server = http.createServer((req, res) => { // req = request from client // res = response to send back res.writeHead(200, {'Content-Type': 'text/html'}); res.write('

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();
💼 Interview Questions (Hinglish)
HTTP aur HTTPS mein kya difference hai? HTTPS kyun secure hai?

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.

req aur res objects mein kya hota hai? Important properties batao.

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)
// Request example http.createServer((req, res) => { console.log('URL:', req.url); // /about console.log('Method:', req.method); // GET console.log('Headers:', req.headers); console.log('User-Agent:', req.headers['user-agent']); });

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
// Response example http.createServer((req, res) => { // Set status and headers res.writeHead(200, { 'Content-Type': 'application/json', 'X-Custom-Header': 'MyValue' }); // Send data const data = { message: 'Success', user: 'John' }; res.end(JSON.stringify(data)); });

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!

Creating HTTP Server
const http = require('http'); const https = require('https'); const fs = require('fs'); // ========== BASIC HTTP SERVER ========== const server = http.createServer((req, res) => { // req = request from client // res = response to send back res.writeHead(200, {'Content-Type': 'text/html'}); res.write('

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();
💼 Interview Questions (Hinglish)
HTTP aur HTTPS mein kya difference hai? HTTPS kyun secure hai?

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.

req aur res objects mein kya hota hai? Important properties batao.

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)
// Request example http.createServer((req, res) => { console.log('URL:', req.url); // /about console.log('Method:', req.method); // GET console.log('Headers:', req.headers); console.log('User-Agent:', req.headers['user-agent']); });

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
// Response example http.createServer((req, res) => { // Set status and headers res.writeHead(200, { 'Content-Type': 'application/json', 'X-Custom-Header': 'MyValue' }); // Send data const data = { message: 'Success', user: 'John' }; res.end(JSON.stringify(data)); });

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

Intermediate
🎯 Simple Explanation

Imagine 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.

⭐ Key Points to Remember
  • 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
ES6+ Features Examples
// Arrow Functions const add = (a, b) => a + b; // Destructuring const { name, age } = user; const [first, second] = array; // Template Literals const message = `Hello, ${name}!`; // Spread Operator const combined = [...arr1, ...arr2]; const merged = { ...obj1, ...obj2 }; // Async/Await async function fetchData() { const data = await fetch(url); return data.json(); }

Express.js Framework

Intermediate
🎯 Simple Explanation

Imagine 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!

⭐ Key Points to Remember
  • 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
Express.js Basics
const express = require('express'); const app = express(); // Middleware app.use(express.json()); // Routes app.get('/', (req, res) => { res.send('Hello World!'); }); app.post('/api/users', (req, res) => { const newUser = req.body; res.status(201).json({ user: newUser }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
💼 Interview Questions (Hinglish)
Middleware kya hai aur kaise kaam karta hai?

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

Intermediate
🎯 Simple Explanation

Imagine 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!

⭐ Key Points to Remember
  • Document-based: Stores data as BSON documents
  • Flexible Schema: No fixed structure
  • Mongoose: ODM library for MongoDB
  • CRUD Operations: Create, Read, Update, Delete
Mongoose Example
const mongoose = require('mongoose'); // Define Schema const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, unique: true }, age: Number }); // Create Model const User = mongoose.model('User', userSchema); // CREATE const newUser = await User.create({ name: 'John', email: 'john@example.com' }); // READ const users = await User.find(); const user = await User.findById(id); // UPDATE await User.findByIdAndUpdate(id, { age: 31 }); // DELETE await User.findByIdAndDelete(id);
💼 Interview Questions (Hinglish)
SQL aur NoSQL mein kya difference hai?

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

Advanced
🎯 Simple Explanation

Imagine 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!

Socket.IO Chat Example
// Server const io = require('socket.io')(http); io.on('connection', (socket) => { console.log('User connected'); socket.on('chat message', (msg) => { io.emit('chat message', msg); // Broadcast to all }); socket.on('disconnect', () => { console.log('User disconnected'); }); }); // Client const socket = io(); socket.emit('chat message', 'Hello!'); socket.on('chat message', (msg) => console.log(msg));

Testing with Jest

Intermediate
🎯 Simple Explanation

Imagine 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!

Jest Testing Example
// math.js function add(a, b) { return a + b; } module.exports = { add }; // math.test.js const { add } = require('./math'); test('adds 1 + 2 to equal 3', () => { expect(add(1, 2)).toBe(3); }); // Async testing test('fetches user data', async () => { const data = await fetchUser(1); expect(data.name).toBe('John'); });

Deployment & Production

Advanced
🎯 Simple Explanation

Imagine 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!

⭐ Key Points to Remember
  • 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

Advanced
🎯 Simple Explanation

Imagine 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!

⭐ Key Points to Remember
  • 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

Advanced
🎯 Simple Explanation

Imagine 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!

⭐ Key Points to Remember
  • 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
↑