[go: up one dir, main page]

0% found this document useful (0 votes)
13 views48 pages

Study Notes2

The document is a comprehensive syllabus for Node.js covering fundamentals, modules, asynchronous programming, file system operations, HTTP and Express.js, API interaction, databases, authentication, error handling, deployment, and testing. It includes detailed explanations, code examples, and interview tips for each topic. The content is structured to prepare individuals for Node.js development and related interviews.

Uploaded by

hackers.iknow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views48 pages

Study Notes2

The document is a comprehensive syllabus for Node.js covering fundamentals, modules, asynchronous programming, file system operations, HTTP and Express.js, API interaction, databases, authentication, error handling, deployment, and testing. It includes detailed explanations, code examples, and interview tips for each topic. The content is structured to prepare individuals for Node.js development and related interviews.

Uploaded by

hackers.iknow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Syllabus

✅ 1. Node.js Fundamentals

Topic Description

Runtime built on Chrome's V8 JS engine


What is Node.js?
(server-side JS).

Single-threaded, Non-blocking I/O model, uses the Event


event-driven Loop for concurrency.

__dirname, __filename, process, Buffer,


Global Objects
setImmediate

🧠 Interview Tip: Explain how Node.js handles many requests with


a single thread.

✅ 2. Modules and Package Management

Concept Details

CommonJS require, module.exports

import, export (with .mjs or "type":


ES Modules
"module")

npm init, npm install, devDeps,


NPM/Yarn
semantic versioning

Local vs Global
-g flag installs globally
Packages

🧠 Interview Tip: Be ready to explain the difference between


CommonJS and ES Modules.

✅ 3. Event Loop & Asynchronous Programming

Concept Example

Event Loop Handles callbacks, timers, async I/O

Microtasks vs
Promise vs setTimeout
Macrotasks

Nested callbacks; solve using


Callback Hell
Promises/async-await
Concept Example

Promises / Async-
Modern async handling
Await

🧠 Interview Q: Explain how the Event Loop works.


✅ Say: "The Event Loop lets Node handle thousands of concurrent
requests using a single thread by queuing operations and running
callbacks."

✅ 4. File System (fs)

js

CopyEdit

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {

if (err) throw err;

console.log(data);

});

Method Purpose

Async file
readFile, writeFile
handling

Promise-based
fs.promises
version

fs.existsSync,
Sync operations
fs.mkdirSync

✅ 5. HTTP Module & Express.js

🧩 Native HTTP server

js

CopyEdit

const http = require("http");

http.createServer((req, res) => {

res.end("Hello World");
}).listen(3000);

🚀 Express.js (Must-Know Framework)

js

CopyEdit

const express = require("express");

const app = express();

app.get("/", (req, res) => res.send("Hi!"));

app.listen(3000);

Topic Description

Routing app.get, app.post

app.use() for auth, logs,


Middleware
error

Body express.json(),
Parsing express.urlencoded()

Error
next(err) pattern
Handling

Static Files express.static()

🧠 Interview Q: What is middleware in Express?


✅ Answer: Middleware are functions that run before the request
reaches the final route handler. Useful for logging,
authentication, etc.

✅ 6. Working with APIs

Tool Usage

axios, fetch Call external APIs

express.Rou
Modular routing
ter()

Status 200 OK, 404 Not Found, 500


Codes Server Error

RESTful
CRUD with HTTP methods
Services
✅ 7. Databases (MongoDB or SQL)

MongoDB (with Mongoose)

js

CopyEdit

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/test");

Operati
Example
on

Create Model.create()

Read Model.find()

Model.findByIdAndUp
Update
date()

Model.findByIdAndDe
Delete
lete()

🧠 Interview Tip: Be ready to talk about schema design, indexes,


relationships (references vs embedding).

✅ 8. Authentication & Authorization

Concept Implementation

jsonwebtoken to create/verify
JWT
tokens

Sessions express-session

Hashing bcrypt for passwords

Role-based Custom middleware based on


access user role

✅ 9. Error Handling & Logging

Practice Tool

Try/catch, async error Handle unexpected


Practice Tool

middleware issues

Pass errors in
next(err)
Express

Logging winston, morgan

✅ 10. Deployment Basics

Platform Notes

Heroku, Vercel,
Easy deploy with Git
Render

Process manager to keep


PM2
server alive

Manage env variables


dotenv
securely

Often used with Nginx in


Reverse proxy
production

✅ 11. Testing

Tool Usage

Jest Unit testing

HTTP route
Supertest
testing

Postman / Thunder Manual API


Client testing

🧠 Interview Q: How do you test an API route?


✅ Answer: I use Supertest to simulate HTTP requests and validate
responses.

Notes
✅ Node.js Fundamentals (3 Years Experience)

🔷 1. What is Node.js?

 Node.js is an open-source, server-side runtime built on


Chrome's V8 JavaScript engine.

 It allows you to run JavaScript outside the browser — mainly for


backend/server apps.

 Written in C++ (for core), JavaScript (APIs), and libuv (for


async I/O).

🧠 Real-world analogy: Think of Node.js as a JavaScript engine that can


talk to your OS to read/write files, listen to network requests, and interact
with databases — all outside the browser.

🔷 2. Single-threaded, Event-driven

 Node.js uses a single thread to handle multiple client requests.

 Instead of waiting (blocking), it uses callbacks, Promises, and the


Event Loop to handle I/O tasks asynchronously.

📌 This is why Node.js is fast and scalable, especially for I/O-heavy apps
(like chat, APIs, real-time apps).

🔁 How does it handle multiple requests?

 Node puts blocking tasks (file read, DB call) in a task queue.

 While the task runs in the background, Node continues processing


other code.

 When the task finishes, the result is added to the callback queue.

 The Event Loop picks it and executes the callback.

✅ No thread per request. One thread, many tasks – non-blocking.


🔷 3. Node.js Global Objects

Global
Description
Object

__dirname Absolute path of current directory

__filename Absolute path of current file

Gives info about the running process (env,


process
memory, args)

Buffer Used to handle binary data

setImmediat
Runs a callback after current event loop phase
e()

js

CopyEdit

console.log(__dirname); // e.g., /home/user/project

console.log(__filename); // e.g., /home/user/project/index.js

💬 Common Interview Questions & Simple Answers

❓ Q1: What is Node.js and why is it used?

✅ Answer:
Node.js is a JavaScript runtime that allows us to run JS outside the
browser, mainly on the server. It’s used to build fast and scalable web
applications, especially APIs and real-time services.

❓ Q2: How is Node.js different from traditional server-side


platforms?

✅ Answer:
Traditional platforms like PHP or Java use multi-threaded blocking I/O.
Node.js is single-threaded and non-blocking, meaning it can handle
many requests simultaneously using callbacks and the event loop.

❓ Q3: What is the Event Loop in Node.js?


✅ Answer:
The Event Loop is what lets Node.js run non-blocking code. It continuously
checks if any callbacks are ready to run, and executes them in a loop —
so Node can do many things at once without threads.

❓ Q4: Explain how Node handles multiple requests on a single


thread.

✅ Answer:
Node puts long-running tasks like file reads or DB queries in the
background. When they’re done, it adds their result to a queue. The Event
Loop picks them up when ready. So Node isn’t “stuck” — it keeps handling
other tasks in the meantime.

❓ Q5: What are some global objects in Node?

✅ Answer:

 __dirname: directory of current file

 __filename: full path of current file

 process: info about environment

 Buffer: binary data

 setImmediate(): run callback immediately after current phase

❓ Q6: Is Node.js good for CPU-heavy tasks?

✅ Answer:
Not ideal. Since Node runs on a single thread, CPU-heavy tasks (like large
calculations) block the event loop. For such tasks, we use Worker
Threads or move them to other services.

✅ Summary for Interview

“Node.js is a fast, scalable backend platform that runs JavaScript outside


the browser using the V8 engine. It’s single-threaded and non-blocking,
meaning it can handle thousands of I/O requests simultaneously using an
event-driven model and the event loop. It exposes global objects like
__dirname, process, and Buffer to help us interact with the system easily.”
✅ 2. Modules and Package Management (Node.js – 3 Years
Experience)

Includes simple explanations, code samples, and frequently asked


interview questions so you can explain them confidently.

🔷 1. CommonJS Modules (Default in Node.js)

 Uses require() and module.exports

 Synchronous loading (ideal for server-side)

Example:

js

CopyEdit

// math.js

function add(a, b) {

return a + b;

module.exports = { add };

// index.js

const math = require('./math');

console.log(math.add(2, 3)); // 5

✅ Used in most existing Node.js projects.

🔷 2. ES Modules (Modern JS – ECMAScript Modules)

 Uses import and export

 Must use .mjs file extension or set "type": "module" in package.json

 Supports top-level await, static analysis, and tree-shaking

Example:

js

CopyEdit

// math.mjs
export function add(a, b) {

return a + b;

// index.mjs

import { add } from './math.mjs';

console.log(add(2, 3));

✅ ES modules are future-facing and align with browser JS.

🧠 Interview Tip: CommonJS vs ES Modules

Feature CommonJS ES Modules

require,
Syntax import, export
exports

Loading Synchronous Asynchronous

Usage in Must opt-in (via .mjs or "type":


Default
Node "module")

Top-level ❌ Not
✅ Supported
await supported

🔷 3. NPM & Yarn – Package Managers

Used to install, update, and manage dependencies in Node.js


projects.

Key Commands:

bash

CopyEdit

npm init # Create package.json

npm install axios # Install as dependency

npm install nodemon --save-dev # Dev dependency

npm uninstall axios


Concept Example

Dependency Installed for app to run

Used during development


Dev Dependency
only

Semantic ^1.2.3 → minor updates


Versioning allowed

package-lock.json or
Lock File
yarn.lock

🔷 4. Local vs Global Packages

Installed Example
Type Use Case
Where? Command

Local Inside project npm install express App-specific packages

Globa npm install -g CLI tools, reusable across


System-wide
l nodemon apps

🧠 Tip: Use global install for tools, local install for app code.

💬 Interview Questions & Simple Answers

❓ Q1: What is the difference between CommonJS and ES Modules?

✅ Answer:
CommonJS uses require() and is synchronous – used by default in Node.js.
ES Modules use import/export and support top-level await – more modern
but need .mjs extension or "type": "module" in package.json.

❓ Q2: What is module.exports used for?

✅ Answer:
To export a function, object, or variable from one file to use it in another
file using require().

❓ Q3: What is the difference between dependencies and


devDependencies?
✅ Answer:

 Dependencies are needed for your app to run (express, axios).

 DevDependencies are needed only during development


(nodemon, jest).

❓ Q4: When would you install a package globally?

✅ Answer:
When you need it available everywhere in your system — for example, CLI
tools like nodemon, eslint.

❓ Q5: What is semantic versioning?

✅ Answer:
A format like 1.2.3:

 1 = major

 2 = minor

 3 = patch
Symbols:

 ^1.2.3 → accept minor/patch updates

 ~1.2.3 → only patch updates

✅ Summary for Interview

“Node.js supports two module systems: CommonJS (require) and ES


Modules (import). CommonJS is default in Node, while ES Modules are
more modern and used with type: "module" or .mjs.
NPM helps manage project dependencies with npm install, dev
dependencies, and semantic versioning. Packages can be installed locally
or globally depending on whether they are app-specific or system-wide
tools.”

✅ 3. Event Loop & Asynchronous Programming

(With examples, simple explanations, and interview Q&A)

🔷 What is the Event Loop?


 The Event Loop is the core mechanism in Node.js that allows
non-blocking, asynchronous behavior on a single-threaded
runtime.

 It processes:

o Callbacks

o Promises

o Timers

o I/O operations

🧠 Why it matters: It helps Node.js handle thousands of concurrent


requests efficiently without multithreading.

📌 Event Loop Phases (Simplified)

1. Call Stack: Executes sync code.

2. Callback Queue (Macrotasks): Timers (setTimeout, setInterval),


I/O callbacks.

3. Microtask Queue: Promises, process.nextTick().

4. Event Loop: Picks tasks from queue and pushes them to the call
stack.

📌 Microtasks vs Macrotasks

Type Examples Executed When?

Microtask Promise.then, queueMicrotask, Immediately after current


s process.nextTick() operation, before macrotasks

Macrotask setTimeout, setInterval,


After all microtasks
s setImmediate

Example:

js

CopyEdit

console.log('Start');

setTimeout(() => console.log('Timeout'), 0); // Macrotask


Promise.resolve().then(() => console.log('Promise')); // Microtask

console.log('End');

// Output:

// Start

// End

// Promise

// Timeout

🔷 Callback Hell

Nested callbacks make code hard to read/maintain.

js

CopyEdit

getUser((err, user) => {

getPosts(user.id, (err, posts) => {

getComments(posts[0], (err, comments) => {

console.log(comments);

});

});

});

✅ Solution: Use Promises or async/await

🔷 Promises

js

CopyEdit

function getData() {

return new Promise((resolve, reject) => {

setTimeout(() => resolve('Data received'), 1000);


});

getData().then(console.log); // Data received

🔷 Async/Await

js

CopyEdit

async function fetchData() {

try {

const data = await getData();

console.log(data);

} catch (err) {

console.error(err);

✅ Makes async code look and behave like sync code.

💬 Common Interview Questions & Sample Answers

❓ Q1: How does the Event Loop work?

✅ Answer:
The Event Loop allows Node.js to handle many I/O operations on a single
thread. It puts async tasks into queues and executes them when the call
stack is clear. This way, Node stays non-blocking and fast.

❓ Q2: What is the difference between microtasks and macrotasks?

✅ Answer:

 Microtasks (Promises) run immediately after the current task.

 Macrotasks (setTimeout, I/O) run after all microtasks are done.


❓ Q3: What is callback hell, and how do you fix it?

✅ Answer:
Callback hell is deeply nested callbacks that are hard to read and debug.
We can fix it using Promises or async/await, which flatten the structure
and improve readability.

❓ Q4: What is the advantage of async/await over Promises?

✅ Answer:
async/await makes code look like synchronous code, which is easier to
read, write, and debug. It also lets us use try/catch for clean error
handling.

❓ Q5: What’s the difference between setImmediate and


setTimeout?

✅ Answer:

 setTimeout(fn, 0) schedules after a minimum delay (~1–4ms).

 setImmediate(fn) runs after the current event loop phase,


immediately after I/O events.

✅ Summary for Interview

“Node.js uses the Event Loop to handle async operations without threads.
It separates tasks into microtasks (Promises) and macrotasks (Timers, I/O),
running them in order of priority. We can avoid callback hell by using
Promises or async/await to write cleaner, more readable async code.”

🔧 Optional Hands-on Exercise

Try this to solidify your understanding:

js

CopyEdit

console.log("1");

setTimeout(() => console.log("2"), 0);


setImmediate(() => console.log("3"));

Promise.resolve().then(() => console.log("4"));

console.log("5");

// Output: 1, 5, 4, 2 or 3 (order of 2/3 may vary by system)

✅ 4. File System (fs) Module in Node.js

(With examples, use cases, and common interview Q&A)

🔷 What is fs?

 The fs (File System) module allows Node.js to interact with the


file system.

 You can read, write, update, rename, and delete files and
directories.

 Offers both asynchronous and synchronous methods.

✅ Preferred: Use async methods for better performance.

🔷 Commonly Used Methods (With Purpose)

Method Purpose

fs.readFile() Asynchronously read file content

fs.writeFile() Asynchronously write/replace file

fs.promises.readFil Read file using Promises / async-


e() await

Check if file or folder exists


fs.existsSync()
(sync)

fs.mkdirSync() Create directory (sync)

📌 Basic Example: Async File Read

js

CopyEdit
const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {

if (err) throw err;

console.log(data);

});

 Non-blocking

 Callback is triggered once the file is read

📌 Writing a File Asynchronously

js

CopyEdit

fs.writeFile('output.txt', 'Hello World!', (err) => {

if (err) throw err;

console.log('File written successfully.');

});

📌 Using Promise-based API (fs.promises)

js

CopyEdit

const fs = require('fs').promises;

async function readMyFile() {

try {

const data = await fs.readFile('file.txt', 'utf8');

console.log(data);

} catch (err) {

console.error(err);

}
}

✅ Cleaner with async/await

📌 Synchronous Methods (Blocking)

js

CopyEdit

const fs = require('fs');

if (fs.existsSync('file.txt')) {

const data = fs.readFileSync('file.txt', 'utf8');

console.log(data);

🛑 Note: Sync methods block the thread — avoid in production if possible.

💬 Common Interview Questions & Simple Answers

❓ Q1: How do you read a file in Node.js?

✅ Answer:
Use fs.readFile() for async or fs.promises.readFile() for async/await. You
pass a path and a callback or use await.

❓ Q2: What is the difference between readFile and readFileSync?

✅ Answer:

 readFile is non-blocking and uses a callback.

 readFileSync is blocking and halts execution until done.

❓ Q3: When should you use synchronous methods?

✅ Answer:
Only in scripts or CLI tools where blocking is acceptable. Avoid in web
servers, as they block the single thread.
❓ Q4: How do you write a file using Promises?

✅ Answer:
Use fs.promises.writeFile() with async/await.

js

CopyEdit

await fs.writeFile('test.txt', 'hello');

❓ Q5: How do you check if a file exists before reading it?

✅ Answer:
Use fs.existsSync(path) — but remember it's sync. For non-blocking, just
try reading the file and handle the error.

✅ Summary for Interview

“Node.js has a built-in fs module for file operations. It provides both sync
and async methods to read, write, and manage files and directories. In
production, we prefer async or fs.promises to keep things non-blocking
and scalable.”

Bonus Tip: Handle Errors Gracefully

Always check for err in callbacks or use try/catch in async functions.

✅ 5. HTTP Module & Express.js

(With examples, use cases, and frequently asked interview Q&A)

🔷 Native HTTP Module (Built-in Node.js)

Used to create basic servers without external dependencies.

js

CopyEdit

const http = require("http");


http.createServer((req, res) => {

res.writeHead(200, { "Content-Type": "text/plain" });

res.end("Hello World");

}).listen(3000);

✅ Good for learning, but not ideal for complex apps (no built-in routing,
middleware, etc.).

🔷 Express.js (Most Popular Node.js Framework)

A minimal & flexible Node.js framework to build APIs and web apps.

js

CopyEdit

const express = require("express");

const app = express();

app.get("/", (req, res) => res.send("Hi!"));

app.listen(3000);

✅ Easy routing, middleware support, error handling, and more.

🔸 Key Express Concepts You Must Know

Concept Description & Example

app.get("/path", handler)
Routing
→ Handle different HTTP methods and URLs

app.use(fn)
Middleware
→ Run logic before routes (auth, logging, validation)

Body Use express.json() and express.urlencoded() to access form


Parsing or JSON body

Error
Use next(err) to pass errors to error-handling middleware
Handling

Static Files app.use(express.static("public")) to serve HTML, CSS, JS, etc.


📌 Middleware Example (Logger)

js

CopyEdit

app.use((req, res, next) => {

console.log(`${req.method} ${req.url}`);

next(); // go to next middleware/route

});

📌 Body Parsing (JSON / Form)

js

CopyEdit

app.use(express.json()); // JSON body

app.use(express.urlencoded({ extended: true })); // HTML form data

js

CopyEdit

app.post("/data", (req, res) => {

console.log(req.body);

res.send("Received");

});

📌 Static File Example

js

CopyEdit

app.use(express.static("public")); // Serves /public/index.html at /

📌 Error Handling Example

js

CopyEdit

app.use((err, req, res, next) => {


console.error(err.stack);

res.status(500).send("Something broke!");

});

Use next(err) in your routes to send errors here.

💬 Common Interview Questions & Sample Answers

❓ Q1: What is middleware in Express?

✅ Answer:
Middleware are functions that execute before the request reaches the
final route handler. They can modify the request/response, log info, check
authentication, or handle errors.

❓ Q2: How do you parse JSON or form data in Express?

✅ Answer:
Use built-in middlewares:

 express.json() for JSON

 express.urlencoded() for form submissions

❓ Q3: How does routing work in Express?

✅ Answer:
Routing defines what to do for different URLs or HTTP methods.
Example:

js

CopyEdit

app.get("/users", ...);

app.post("/users", ...);

❓ Q4: How does Express handle errors?

✅ Answer:
If you pass an error to next(err), it is caught by error-handling middleware:
js

CopyEdit

app.use((err, req, res, next) => { ... });

❓ Q5: What's the difference between http and Express?

✅ Answer:

 http is basic and low-level.

 Express adds routing, middleware, body parsing, and other


features for building apps easily.

✅ Summary for Interview

“Node.js has a built-in http module for creating basic servers. Express.js
builds on top of that and provides powerful features like routing,
middleware, static file serving, body parsing, and error handling. It’s the
standard for building scalable web APIs in Node.”

Optional Hands-on Tasks

 Build a simple REST API (GET, POST, PUT, DELETE) using Express

 Create a middleware for logging all requests

 Build a contact form using Express + body parsing

✅ 6. Working with APIs (Node.js & Express)

With examples, concepts, and common interview Q&A so you can


confidently explain in interviews.

🔷 What is an API?

An API (Application Programming Interface) allows two systems to


communicate. In Node.js/Express, we often build REST APIs that expose
endpoints to clients (frontend, mobile apps, 3rd-party systems).

🔹 Tools & Concepts


Tool /
Description / Usage
Concept

fetch, axios Make external API requests (client or server-side)

express.Router
Organize routes in modular files
()

Inform client of response status (e.g., 200 OK, 404


Status Codes
Not Found)

RESTful CRUD operations using HTTP verbs: GET, POST, PUT,


Services DELETE

🔸 1. Calling External APIs (Client or Server)

📌 Using axios (Popular & Promise-based)

js

CopyEdit

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts/1')

.then(res => console.log(res.data))

.catch(err => console.error(err));

📌 Using fetch (built-in in browser, needs node-fetch in Node.js)

js

CopyEdit

const fetch = require('node-fetch');

fetch('https://api.example.com/data')

.then(res => res.json())

.then(data => console.log(data));

✅ Use async/await for cleaner syntax.

🔸 2. express.Router() – Modular Routing


js

CopyEdit

// routes/userRoutes.js

const express = require('express');

const router = express.Router();

router.get('/profile', (req, res) => {

res.send('User profile');

});

module.exports = router;

// app.js

const userRoutes = require('./routes/userRoutes');

app.use('/user', userRoutes);

✅ Keeps large APIs organized by grouping routes.

🔸 3. HTTP Status Codes (Most Common)

Cod
Meaning When to Use
e

Successful GET or
200 OK
POST

After creating a
201 Created
resource

400 Bad Request Invalid input

401 Unauthorized Not logged in

403 Forbidden No permission

Route or resource
404 Not Found
missing

500 Internal Server Uncaught server error


Cod
Meaning When to Use
e

Error

js

CopyEdit

res.status(404).json({ message: "User not found" });

🔸 4. RESTful API Basics

Use HTTP methods for CRUD:

Metho Actio
URL Example
d n

/users or
GET Read
/users/:id

Creat
POST /users
e

Updat
PUT /users/:id
e

DELET
Delete /users/:id
E

js

CopyEdit

// Example route

app.get('/users', (req, res) => {

res.json([{ id: 1, name: 'Alice' }]);

});

💬 Common Interview Questions & Sample Answers

❓ Q1: What tools do you use to call external APIs in Node.js?


✅ Answer:
I use Axios for external API calls. It supports Promises, automatic JSON
parsing, and better error handling than the native fetch.

❓ Q2: What is express.Router() and why is it used?

✅ Answer:
It allows us to modularize our routes into separate files for better code
organization. It makes large APIs easier to maintain.

❓ Q3: How do you handle different HTTP status codes?

✅ Answer:
Use res.status(code).json() to return a response. For example, 200 for
success, 404 for not found, and 500 for server errors.

❓ Q4: What is a REST API and how do you build one in Express?

✅ Answer:
A REST API uses HTTP methods to perform CRUD operations. In Express,
we create routes like GET /users, POST /users, and use controllers or
handlers to process requests.

❓ Q5: What’s the difference between PUT and PATCH?

✅ Answer:

 PUT replaces the whole resource.

 PATCH updates only part of the resource.

✅ Summary for Interview

“In Node.js and Express, we create REST APIs to handle client requests
using routes and HTTP methods. We use tools like Axios or Fetch to make
external API calls. Express provides express.Router() for modular route
handling. We also use standard HTTP status codes to inform clients about
the result of their requests.”

Optional Practice Tasks


 🔧 Build a REST API for products with CRUD routes.

 🌐 Call an external API (e.g., weather API) and return data to the
client.

 🧪 Use express.Router() to split routes into multiple files.

✅ 7. Databases (MongoDB with Mongoose)

With examples, key concepts, and top interview questions so you can
explain confidently in interviews.

🔷 What is MongoDB?

 MongoDB is a NoSQL database that stores data in JSON-like


documents.

 It’s schema-less, flexible, and ideal for projects where the structure
can evolve.

 Mongoose is an ODM (Object Data Modeling) library for MongoDB


in Node.js.

🔷 Mongoose Setup

js

CopyEdit

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/test")

.then(() => console.log("Connected"))

.catch(err => console.error(err));

✅ Connects to a local MongoDB database called test.

🔷 Define a Schema & Model

js

CopyEdit

const userSchema = new mongoose.Schema({


name: String,

email: String,

age: Number

});

const User = mongoose.model("User", userSchema);

✅ Defines a collection structure (User collection in MongoDB).

🔷 CRUD Operations in Mongoose

Operati
Example
on

User.create({ name: "Alice", email:


Create
"a@x.com" })

Read User.find() or User.findById(id)

Update User.findByIdAndUpdate(id, { age: 25 })

Delete User.findByIdAndDelete(id)

🧠 Interview Tip: Be prepared to discuss:

🔸 1. Schema Design

 Choose correct types and required fields.

 Use default, validate, and enum to enforce structure.

js

CopyEdit

age: { type: Number, required: true, min: 0 }

🔸 2. Indexes

 Used to speed up queries.

 Can be single-field, compound, or unique.

js
CopyEdit

userSchema.index({ email: 1 }, { unique: true });

🔸 3. Relationships: Embedding vs Referencing

Type Description When to Use

Embeddin Nest documents inside Use when tightly coupled (e.g.,


g others comments inside a post)

Referenci Use ObjectId to refer to Use when decoupled or reused


ng another document elsewhere (e.g., user in orders)

js

CopyEdit

// Referencing example:

postSchema = new mongoose.Schema({

user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }

});

💬 Common Interview Questions & Answers

❓ Q1: What is the difference between MongoDB and SQL


databases?

✅ Answer:
MongoDB is a NoSQL, document-based database. It’s flexible and doesn’t
require a fixed schema. SQL databases use tables and schemas with
strict structure. MongoDB is better for rapid development and hierarchical
data.

❓ Q2: What is Mongoose and why use it?

✅ Answer:
Mongoose is an ODM for MongoDB that lets you define schemas, validate
data, and interact with the database using models. It simplifies MongoDB
usage in Node.js.
❓ Q3: What’s the difference between embedding and referencing
in MongoDB?

✅ Answer:

 Embedding stores related data inside a document.

 Referencing uses an ObjectId to link to another document.

Embedding is faster for read-heavy, tightly coupled data. Referencing is


better for large, shared, or loosely related data.

❓ Q4: How do you handle schema validation in Mongoose?

✅ Answer:
In the schema definition, use type, required, min, enum, etc. Mongoose
will validate data before saving.

❓ Q5: What is a unique index in MongoDB?

✅ Answer:
A unique index ensures that no two documents can have the same value
for a field. Example: unique email for each user.

js

CopyEdit

userSchema.index({ email: 1 }, { unique: true });

✅ Summary for Interview

“MongoDB is a NoSQL database that stores flexible, JSON-like documents.


In Node.js, we use Mongoose to define schemas and models. Mongoose
provides CRUD methods, validation, and relationship management
through embedding or referencing. Indexes improve performance, and
schema design helps enforce data integrity.”

🔧 Optional Practice Tasks

 ✅ Build a User model and implement CRUD routes in Express.

 🧪 Try embedding comments inside a Post, and referencing users in


orders.

 🔍 Add a unique index to an email field and test validation.


✅ 8. Authentication & Authorization in Node.js

With simple explanations, real-world examples, and frequently asked


interview questions & answers.

🔷 What's the Difference?

Concept Meaning

Authenticat
Confirms who the user is (login/signup).
ion

Authorizati Confirms what the user can do (based on


on roles/permissions).

🔸 Common Auth Tools & Concepts

Tool/Concept Purpose

JWT Token-based login for APIs


(jsonwebtoken) (stateless)

bcrypt Securely hash passwords

express-
Server-side sessions (cookies)
session

Role-based Allow/deny routes based on


Access user role

🔷 1. JWT Authentication (Stateless)

 JWT = JSON Web Token

 Sent in HTTP headers, stored in localStorage or cookies

 Contains encoded user info

bash

CopyEdit

npm install jsonwebtoken

📌 Sign a JWT:
js

CopyEdit

const jwt = require("jsonwebtoken");

const token = jwt.sign({ id: user._id, role: user.role }, "secretKey",


{ expiresIn: "1h" });

📌 Verify a JWT:

js

CopyEdit

const decoded = jwt.verify(token, "secretKey");

✅ Used for REST APIs

🔷 2. bcrypt for Password Hashing

bash

CopyEdit

npm install bcrypt

📌 Hash a password:

js

CopyEdit

const bcrypt = require("bcrypt");

const hashedPassword = await bcrypt.hash("mypassword", 10);

📌 Compare password:

js

CopyEdit

const isMatch = await bcrypt.compare("inputPassword",


user.hashedPassword);

✅ Always hash passwords before storing them in DB.

🔷 3. express-session (Server-side Sessions)

bash

CopyEdit
npm install express-session

📌 Setup:

js

CopyEdit

const session = require('express-session');

app.use(session({

secret: 'mysecret',

resave: false,

saveUninitialized: true

}));

✅ Session is stored in memory or external store (like Redis).

🔷 4. Role-Based Authorization (Custom Middleware)

js

CopyEdit

function authorizeRoles(...roles) {

return (req, res, next) => {

if (!roles.includes(req.user.role)) {

return res.status(403).json({ message: "Access denied" });

next();

};

// Example usage

app.get('/admin', authenticateToken, authorizeRoles('admin'), (req, res)


=> {

res.send("Welcome Admin");

});
✅ Good for apps with admin, user, manager roles.

💬 Common Interview Questions & Sample Answers

❓ Q1: What is JWT and how does it work?

✅ Answer:
JWT stands for JSON Web Token. It’s used for stateless authentication.
After login, the server creates a token with user info, which the client
stores and sends with every request. The server verifies the token to
authenticate the user.

❓ Q2: Why do we hash passwords?

✅ Answer:
Hashing passwords using bcrypt ensures that even if the database is
hacked, the original passwords aren’t exposed. It’s a one-way function
that makes passwords unreadable.

❓ Q3: What's the difference between session-based and token-


based auth?

✅ Answer:

Feature Session-based Token-based (JWT)

Stateless, client stores


State Server stores session
token

Cookie + server
Storage Header or localStorage
memory/DB

Scalabilit Harder with multiple Easier (token is self-


y servers contained)

❓ Q4: How do you implement role-based access?

✅ Answer:
We add a role field to the user and create middleware that checks if the
logged-in user's role is allowed to access a route.
❓ Q5: What’s in a JWT?

✅ Answer:

 Header: algorithm & type

 Payload: user info like ID, role

 Signature: verifies token wasn't tampered with

✅ Summary for Interview

“Authentication confirms who the user is, and authorization confirms what
the user can do. JWT is used for stateless login, bcrypt for hashing
passwords, and role-based middleware protects sensitive routes. Sessions
can be used for stateful login, typically with cookies.”

🧪 Optional Practice

 🔐 Build an Express login API using JWT

 🔏 Add bcrypt hashing and secure password check

 🔒 Create middleware for admin-only access

✅ 9. Error Handling & Logging in Node.js & Express

With clear explanations, examples, and common interview questions &


answers

🔷 Why It Matters

In real-world apps, you need to handle unexpected errors gracefully and


log them properly for debugging and maintenance.

🔸 1. Try/Catch in Async Code

Use try/catch inside async functions to catch errors.

js

CopyEdit

app.get("/user/:id", async (req, res, next) => {

try {
const user = await getUserById(req.params.id);

res.json(user);

} catch (err) {

next(err); // Forward to error middleware

});

🔸 2. next(err) in Express

If something goes wrong inside middleware or route handlers, use


next(err) to pass control to the error-handling middleware.

🔹 Global Error Middleware Example

js

CopyEdit

app.use((err, req, res, next) => {

console.error(err.stack); // You can replace with a logger

res.status(500).json({ message: "Something went wrong!" });

});

✅ Place this after all routes.

🔸 3. Logging Tools

Tool Purpose

morga Logs HTTP requests (method, URL, status) — great for


n development

winsto General-purpose logging tool — write to files, DB, cloud,


n etc.

📌 morgan Setup

bash

CopyEdit
npm install morgan

js

CopyEdit

const morgan = require("morgan");

app.use(morgan("dev")); // Logs request details in console

📌 winston Setup (Simple)

bash

CopyEdit

npm install winston

js

CopyEdit

const winston = require("winston");

const logger = winston.createLogger({

transports: [

new winston.transports.Console(),

new winston.transports.File({ filename: "errors.log" }),

],

});

logger.error("This is an error message");

✅ Winston helps with file logging, log levels, and custom formatting.

💬 Common Interview Questions & Answers

❓ Q1: How do you handle errors in async functions?

✅ Answer:
Wrap the code in a try/catch block and pass errors to next(err) to forward
them to Express’s error-handling middleware.
❓ Q2: What is the role of next(err) in Express?

✅ Answer:
It’s used to pass errors to the global error handler, where you can send
a proper response or log the error.

❓ Q3: What is morgan used for?

✅ Answer:
Morgan logs incoming HTTP requests — it shows method, URL,
response time, and status. Helpful for debugging routes.

❓ Q4: What is winston and when would you use it?

✅ Answer:
Winston is a versatile logging library for structured logs. You can log
errors, info, or debug messages to files or external systems.

❓ Q5: Why is centralized error handling important?

✅ Answer:
It ensures consistent error responses, better debugging, and
separation of logic. It also prevents app crashes by catching unhandled
exceptions.

✅ Summary for Interview

“In Node.js/Express, we use try/catch blocks and next(err) to catch and


forward errors to centralized error middleware. For logging, we use
morgan to log HTTP requests and winston to log application-level errors to
files or services.”

✅ Optional Practice Tasks

 🛠 Add error handling to your Express CRUD API

 🧪 Set up morgan and winston together

 🔐 Trigger an error route and test global error middleware


✅ 10. Deployment Basics (Node.js)

With tools, simple explanations, and common interview questions &


answers.

🔷 Why Deployment Matters

Once you finish developing your app, you need to host it online so users
can access it. Deployment also includes keeping your app running,
handling crashes, and managing environment settings securely.

🔸 1. Platforms for Easy Deployment

Platfor
Notes
m

Free tier, easy CLI deployment, used for backend


Heroku
APIs

Great for frontend (Next.js), supports serverless


Vercel
functions

Free & simple like Heroku, supports backend


Render
servers

📌 Example (Heroku CLI Deploy):

bash

CopyEdit

git init

heroku create

git push heroku main

🔸 2. PM2 – Process Manager for Node.js

PM2 is used in production environments to:

 Keep your app alive (auto-restarts on crash)

 Monitor performance

 Log output to files

📌 Install & Use:


bash

CopyEdit

npm install -g pm2

pm2 start app.js # Start your app

pm2 logs # View logs

pm2 restart app # Restart

pm2 stop app # Stop

✅ Used on VPS (like DigitalOcean, AWS EC2).

🔸 3. dotenv – Secure Env Variables

Don’t hard-code secrets like API keys or database passwords.

bash

CopyEdit

npm install dotenv

📌 .env file:

ini

CopyEdit

PORT=3000

DB_URL=mongodb://localhost/test

📌 In app.js:

js

CopyEdit

require('dotenv').config();

console.log(process.env.PORT);

✅ Keeps sensitive data out of codebase.

🔸 4. Reverse Proxy with Nginx

In production, Nginx is used to:


 Forward HTTP requests to Node.js app

 Load balancing

 Serve static files

📌 Common Setup:

nginx

CopyEdit

server {

listen 80;

location / {

proxy_pass http://localhost:3000;

✅ Keeps Node.js behind a fast, secure proxy.

💬 Common Interview Questions & Answers

❓ Q1: How do you deploy a Node.js app?

✅ Answer:
You can use platforms like Heroku or Render for easy deployment. You
push your code using Git, set environment variables, and the platform
runs your app on the cloud.

❓ Q2: What is PM2 and why is it used?

✅ Answer:
PM2 is a process manager for Node.js. It ensures your app runs
continuously, restarts it on crashes, and provides performance
monitoring and logging features.

❓ Q3: What is dotenv used for?


✅ Answer:
The dotenv package loads environment variables from a .env file so
that sensitive data (like API keys) isn’t hardcoded in your app.

❓ Q4: Why use a reverse proxy like Nginx?

✅ Answer:
Nginx can forward client requests to your Node.js app. It improves
security, performance, and allows serving static files or multiple apps
behind one domain.

❓ Q5: What are some common environment variables in Node


apps?

✅ Answer:

 PORT: What port your app listens on

 DB_URL: Database connection string

 NODE_ENV: development or production

✅ Summary for Interview

“To deploy a Node.js app, we use platforms like Heroku or Render. For
production reliability, PM2 keeps the app running. Environment variables
are managed using dotenv. And we often use Nginx as a reverse proxy in
production to improve performance and security.”

🔧 Optional Practice Tasks

 Deploy a simple Express app on Render or Heroku

 Add a .env file with sensitive variables

 Start your app using PM2 and monitor it

 Write a sample nginx.conf for reverse proxy

✅ 11. Testing in Node.js (Jest, Supertest, Postman)

Plus bonus must-know extras and common interview Q&A.


🔷 Node.js Testing Tools

Tool Purpose

Unit testing, mocking,


Jest
coverage

Automated API testing (HTTP


Supertest
calls)

Postman / Thunder
Manual API testing via GUI
Client

🔸 1. Jest (Unit Testing)

Install:

bash

CopyEdit

npm install --save-dev jest

Add script in package.json:

json

CopyEdit

"scripts": {

"test": "jest"

Sample Test (math.test.js):

js

CopyEdit

const sum = (a, b) => a + b;

test("adds numbers", () => {

expect(sum(2, 3)).toBe(5);

});

✅ Use for pure functions, utility logic, and mocks.


🔸 2. Supertest (API Testing)

Used to simulate HTTP requests to your Express routes.

bash

CopyEdit

npm install --save-dev supertest

Sample Test:

js

CopyEdit

const request = require('supertest');

const app = require('../app'); // your Express app

describe("GET /api", () => {

it("should return 200", async () => {

const res = await request(app).get("/api");

expect(res.statusCode).toBe(200);

expect(res.body.message).toBe("Hello");

});

});

✅ Use to test routes and middleware.

🔸 3. Postman / Thunder Client

 GUI tools to manually test APIs

 Good for testing tokens, body data, error cases

 Not automated — best for quick checks or demos

💬 Sample Interview Q:

How do you test an API route?

✅ Answer:
I use Supertest with Jest to simulate HTTP requests and validate the
response status, headers, and body. It’s useful for ensuring API behavior is
correct.

✅ Bonus Topics (Nice to Know)

Topic Description

Use fs.createReadStream() for large file reading without


Streams
loading whole file in memory.

Enables Node.js to use all CPU cores to handle concurrent


Cluster
traffic.

For real-time applications like chat or notifications (uses


Socket.IO
WebSocket).

Controls which domains can access your API (Cross-Origin


CORS
Resource Sharing).

Rate Use express-rate-limit to block abuse, like too many login


Limiting attempts.

📌 Sample Interview Questions & Simple Answers

Question Answer

A mechanism that allows Node.js to


What is the Event Loop? handle many operations asynchronously
using a single thread.

It loads and caches a CommonJS module.


How does require() work?
Once loaded, it won’t be loaded again.

Difference between
nextTick runs before I/O, setImmediate
process.nextTick() and
runs after I/O events in the event loop.
setImmediate()?

Use try/catch for async/await, .catch() for


How to handle errors in
Promises, and next(err) for Express
async code?
middleware.

Use input validation, HTTPS, JWT for auth,


How to secure Node APIs? CORS, rate limiting, and sanitize inputs to
prevent injection.
✅ Summary for Interview

“I test APIs using Supertest for automated HTTP testing and Jest for unit
tests. For manual testing, I use Postman. I also understand important
backend topics like the event loop, real-time communication with
Socket.IO, and securing APIs using best practices like rate limiting and
CORS.”

🔧 Optional Practice Tasks

 ✅ Write unit tests for utility functions using Jest

 🌐 Build & test an Express route using Supertest

 🔒 Implement CORS and rate limiting on your API

 📡 Add a WebSocket-based notification with Socket.IO

You might also like