CORPORATE
Section 1: [Link] Fundamentals
Globals in [Link]
[Link] provides several global objects available without requiring modules:
• global: The global namespace (like window in browsers). Use for sharing variables
across modules (e.g., [Link] = {};).
• process: Info about the current process (e.g., [Link].NODE_ENV, [Link]
for CLI args, [Link]() for current directory).
• console: For logging (e.g., [Link](), [Link]()).
• Buffer: For handling binary data.
• __dirname / __filename: Path to current directory/file.
• setTimeout / setInterval / setImmediate: Timers.
• require / module / exports: For module loading.
Best Practice: Avoid polluting global in production; use it sparingly for cross-module state.
How to Check if a Package is Safe to Use
1. npm Audit: Run npm audit in your project to scan for vulnerabilities. It checks
against the npm security database and suggests fixes (e.g., npm audit fix).
2. Snyk or Dependabot: Integrate tools like Snyk (CLI: snyk test) for deeper scans,
including transitive dependencies.
3. GitHub Security Alerts: If using GitHub, enable Dependabot for automated vuln
alerts.
4. Check Package Stats: Use npm info <package> for downloads/maintainer info; sites
like [Link] or [Link] for trends (low downloads = potential risk).
5. Read Reviews: Check GitHub stars, issues, last commit date (>6 months inactive =
risky), and security advisories.
6. Alternatives: Use npm ls --depth=0 to list deps; prefer well-maintained ones like
Lodash over obscure forks.
Tip: Always pin versions in [Link] and update regularly with npm update.
Async/Await Parallel
Async/await is sequential by default, but for parallel execution:
• Use [Link]() with an array of promises:
javascript
async function parallelTasks() {
const [result1, result2] = await [Link]([
fetchData1(), // Promise 1
fetchData2() // Promise 2
]);
CORPORATE
return { result1, result2 };
}
• For dynamic parallels: [Link]() (waits for all, even failures).
• Benefits: Faster than sequential (e.g., API calls run concurrently).
• Error Handling: Wrap in try-catch; failures reject the whole [Link].
[Link], [Link], [Link]
• [Link]([p1, p2]): Waits for all to resolve; returns array of results. Rejects if any
fails (short-circuits on first error). Use for parallel success-required tasks.
javascript
[Link]([[Link](1), [Link](2)]).then(results =>
[Link](results)); // [1, 2]
• [Link]([p1, p2]): Resolves/rejects with the first settled promise (fastest).
Useful for timeouts.
javascript
[Link]([fetchData(), timeout(5000)]); // Rejects if timeout
first
• [Link]([p1, p2]): Waits for all; returns array of {status:
'fulfilled'/'rejected', value/reason}. Ignores individual failures.
javascript
[Link]([[Link](1),
[Link]('Error')]).then(results => [Link](results));
// [{status: 'fulfilled', value: 1}, {status: 'rejected', reason:
'Error'}]
Use Cases: all for batch ops; race for deadlines; allSettled for resilient logging.
Routing in [Link]
Routing defines endpoints for HTTP methods (GET/POST/etc.). Use [Link]() or router for
modularity.
javascript
const express = require('express');
const app = express();
const router = [Link]();
CORPORATE
// Basic route
[Link]('/users', (req, res) => [Link]({ users: [] }));
// Chained methods
[Link]('/book')
.get((req, res) => [Link]('Get book'))
.post((req, res) => [Link]('Add book'));
// Router for /admin
[Link]('/users', (req, res) => { /* ... */ });
[Link]('/admin', router);
[Link](3000);
• Params: /users/:id (access via [Link]).
• Query: ?name=John ( [Link] ).
• Best Practice: Group routes in files (e.g., routes/[Link]); use middleware for auth.
Middleware in [Link]
Middleware are functions that process requests/responses (e.g., logging, auth). Executed in
order.
• Types: Application-level ([Link]()), Router-level ([Link]()), Error-handling (4
args: (err, req, res, next)).
javascript
// Logging middleware
[Link]((req, res, next) => {
[Link](`${[Link]} ${[Link]}`);
next(); // Pass to next middleware
});
// Auth middleware
const auth = (req, res, next) => {
if ([Link]) return next();
[Link](401).send('Unauthorized');
};
[Link]('/protected', auth, (req, res) => [Link]('Secret'));
CORPORATE
// Error middleware (last)
[Link]((err, req, res, next) => {
[Link](500).send([Link]);
});
• Order Matters: Place general (e.g., CORS) first, route-specific last.
• Built-in: [Link]() for body parsing.
Event-Driven Development, Event Emitter, Digest
• Event-Driven: [Link] architecture where code responds to events (non-blocking
I/O). E.g., HTTP requests trigger events.
• EventEmitter: Core class from events module for custom events.
javascript
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
[Link]('event', (data) => [Link]('Event fired:', data)); //
Listener
[Link]('event', { id: 1 }); // Emit
o Methods: on()/addListener() (attach), once() (single fire), removeListener(),
emit().
o Max listeners: Set via [Link](n).
• Digest: In Node context, often refers to "digest cycle" in event loop (process events
until empty). Or crypto digest (hashing, e.g., [Link]('sha256').digest()).
Advantages: Scalable for real-time apps (e.g., chat).
How to Deal with Unhandled Exceptions (Not Captured in Try-Catch)
Unhandled errors crash Node. Handle globally:
javascript
// Unhandled rejections (async)
[Link]('unhandledRejection', (reason, promise) => {
[Link]('Unhandled Rejection:', reason);
// Log, cleanup, or exit
});
// Uncaught exceptions (sync/async)
[Link]('uncaughtException', (err) => {
CORPORATE
[Link]('Uncaught Exception:', err);
[Link](1); // Exit gracefully
});
// For domains (deprecated, use async_hooks instead for advanced)
• Best Practice: Use domains or zones for scoping; always wrap in try-catch for
promises; monitor with PM2/New Relic.
• Warning: Don't ignore; they indicate bugs.
API Development in Node Using Different Methods
• RESTful: Use Express for CRUD (GET/POST/PUT/DELETE). E.g., /api/users (GET
all, POST create).
• GraphQL: Use Apollo Server; define schema, resolvers.
javascript
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`type Query { hello: String }`;
const resolvers = { Query: { hello: () => 'World' } };
new ApolloServer({ typeDefs, resolvers }).listen();
• gRPC: For microservices; define .proto, use grpc-js.
• WebSockets: For real-time ([Link]).
• Methods: Sync (blocking, rare), Async (promises/async-await), Streams (for large
data).
Scalability: Add rate-limiting (express-rate-limit), validation (Joi).
npm vs Yarn: Differences and Which is Better
Feature npm Yarn
Speed Slower (sequential installs) Faster (parallel, cache)
Lockfile [Link] [Link] (more reliable)
Deterministic v5+ yes Always (offline mode)
Workspaces Basic Advanced (monorepos)
Scripts Standard Plug'n'Play (PnP) option
• Differences: Yarn uses yarn add vs npm install; better error handling in Yarn.
• Which Better?: Yarn for speed/monorepos (e.g., large projects); npm for simplicity
(default in Node). Use Yarn v2+ for modern features.
[Link] Details
CORPORATE
Root file for project metadata:
json
{
"name": "my-app",
"version": "1.0.0",
"description": "App desc",
"main": "[Link]", // Entry point
"scripts": { "start": "node [Link]", "test": "jest" },
"dependencies": { "express": "^4.18.0" }, // Runtime deps
"devDependencies": { "jest": "^29.0.0" }, // Build/test deps
"engines": { "node": ">=18.0.0" }, // Node version
"keywords": ["node", "api"],
"author": "You",
"license": "MIT"
}
• Scripts: Run with npm run <script>.
• Bin: For CLI tools.
Dependency vs Dev Dependency
• Dependencies: Required in production (e.g., Express for API).
• DevDependencies: Only for development/testing (e.g., Jest, Nodemon). Installed with
npm i -D <pkg>.
• Impact: npm install --production skips devDeps for smaller prod bundles.
How Node Detects Dev or Prod Env
• Via [Link].NODE_ENV (set externally, e.g., NODE_ENV=production node
[Link]).
• Defaults to 'development'.
• Use in code: if ([Link].NODE_ENV === 'production') { /* optimize */ }.
• Tools: dotenv for .env files; Heroku sets it automatically.
What is LTS in Node Version
Long Term Support (LTS): Stable Node versions supported for 30 months (18 months
active, 12 maintenance). E.g., Node 20 (LTS until 2026). Use for production; "Current" for
bleeding-edge features.
Localization in Node
• Use i18n package:
CORPORATE
javascript
const i18n = require('i18n');
[Link]({ locales: ['en', 'fr'], directory: './locales' });
[Link]([Link]);
[Link].t('hello'); // Translates 'hello' key
• Files: ./locales/[Link] { "hello": "Hello" }.
• Detect locale via [Link]['accept-language'] or URL.
Subprocess in Node (e.g., Run Binary, Get Output)
Use child_process:
javascript
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
[Link]('data', (data) => {
[Link](`Output: ${data}`); // Use in Node
});
[Link]('data', (data) => [Link](`Error: ${data}`));
[Link]('close', (code) => [Link](`Exited with ${code}`));
• spawn: Streaming output (good for large binaries).
• exec: Buffers output (simpler for small cmds).
• Use: Run FFmpeg for video processing, pipe results to Node.
How to Authenticate and Authorize in Node
• Auth (Who are you?): JWT, Sessions (express-session), OAuth ([Link]).
• Authz (What can you do?): Role-based (RBAC) via middleware.
javascript
// JWT Auth
const jwt = require('jsonwebtoken');
[Link]('/login', (req, res) => {
// Verify creds
const token = [Link]({ userId: 1, role: 'admin' }, 'secret', {
expiresIn: '1h' });
[Link]({ token });
CORPORATE
});
const auth = (req, res, next) => {
const token = [Link]('Authorization');
try {
const decoded = [Link](token, 'secret');
[Link] = decoded;
next();
} catch (e) { [Link](401).send('Invalid token'); }
};
[Link]('/protected', auth, (req, res) => [Link]({ data: 'Secret' }));
• Authorize: Check [Link] === 'admin'.
Which Token Mechanism Familiar (e.g., JWT Token Lifetime, Info,
Algorithm)
• JWT (JSON Web Token): Stateless, signed token ([Link]).
o Info: Payload (claims: iss, sub, exp, custom like {userId:1}).
o Lifetime: Set via expiresIn (e.g., '7d'); defaults to none (indefinite, risky).
o Algorithm: HS256 (symmetric, fast) or RS256 (asymmetric, secure). Use
[Link](payload, secret, { algorithm: 'HS256' }).
• If No Lifetime Passed: Token never expires (use refresh tokens for rotation).
• Others: Session cookies (server-side), OAuth2 (for social).
If I Haven't Passed Lifetime, How Long Token Will Survive
Forever (no expiration). Always set exp claim or expiresIn to avoid security risks; use short-
lived access tokens (15min) + long-lived refresh tokens.
Section 2: Databases (SQL & NoSQL)
Stored Procedure in SQL
Pre-compiled SQL code stored in DB for reuse (e.g., MySQL/PostgreSQL).
sql
DELIMITER //
CREATE PROCEDURE GetUser(IN userId INT)
BEGIN
SELECT * FROM users WHERE id = userId;
END //
CORPORATE
DELIMITER ;
CALL GetUser(1);
• Benefits: Performance (cached), security (no direct SQL injection), modularity.
• Call from Node: Use mysql2: [Link]('CALL GetUser(?)', [1], (err, rows)
=> { ... });.
MongoDB: How to Join 2 Tables (No Aggregate)
MongoDB is document-based (no traditional joins). Use:
• $lookup in Aggregation Pipeline (for "joins"):
javascript
[Link]([
{ $match: { _id: ObjectId("...") } },
{ $lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "orders"
}
}
]);
• Population (with Mongoose): See below.
• Denormalization: Embed related data to avoid joins.
Benefits of Using Mongoose
• Schema Validation: Enforce structure (e.g., required fields).
• ODM Features: Middleware (pre/post hooks), population for joins, queries with
chaining.
• TypeScript Support: Built-in types.
• Plugins: Easy extensions (e.g., timestamps, pagination).
• Vs Core MongoDB: Abstracts boilerplate; handles connections, errors.
Aggregate Functions in MongoDB
Pipeline for advanced queries (group, sort, etc.):
javascript
[Link]([
{ $match: { date: { $gte: ISODate("2025-01-01") } } },
CORPORATE
{ $group: { _id: "$product", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
]);
• Functions: $sum, $avg, $min/$max, $push (array), $addFields.
What Are 2D Indexes and Partial Indexes
• 2D Indexes: Geospatial (for lat/long queries). E.g., [Link]({ location:
"2dsphere" }); query with $near/$geoWithin.
• Partial Indexes: Index subset of docs matching filter. E.g., [Link]({
email: 1 }, { partialFilterExpression: { status: "active" } }). Saves space for sparse
data.
Section 3: DevOps & Containers
Containerization Like Docker and Kubernetes
• Docker: Packages app + deps into containers (lightweight VMs). Benefits:
Portability, isolation, versioning.
• Kubernetes (K8s): Orchestrates containers (scaling, load balancing, self-healing).
E.g., Pods (units), Deployments (replicas), Services (exposure).
How Docker Works and Benefits
• Works: Dockerfile defines image (FROM node:18, COPY, RUN npm install). docker
build -t myapp .; docker run myapp.
• Benefits: Consistent envs (dev=prod), fast startup, resource efficiency, easy CI/CD.
SVN or GIT: Purpose of Creating Different Branches in Git
• SVN: Centralized VCS; branches for isolation but less flexible.
• Git: Distributed; branches for features (feature-branch), releases (hotfix),
experiments. Purpose: Parallel dev without affecting main; merge via PRs.
Scenario: Created Branch from Master, Committed Changes, Realized
Should Be from Development. Steps?
1. git checkout master (switch back).
2. git checkout -b new-feature development (create new branch from dev).
3. git cherry-pick <commit-hash> (apply commits from old branch).
4. Delete old branch: git branch -D old-feature.
5. Push: git push origin new-feature.
What is Git Rebase and Git Cherry-pick
CORPORATE
• Rebase: Moves commits to new base (linear history). git rebase development (replays
commits on dev). Vs merge: Cleaner but rewrites history (avoid on shared branches).
• Cherry-pick: Applies specific commit to another branch. git cherry-pick <hash>. Use
for hotfixes.
Agile Methodology: What Are You Following
Agile: Iterative dev with sprints (2-4 weeks). I follow Scrum: Daily standups, sprint
planning, retrospectives, backlog grooming. Tools: Jira/Trello. Vs Kanban: Flow-based for
maintenance.
Section 4: Frameworks vs Runtime, Node vs Express,
Client vs Browser
Framework vs Runtime Env
• Runtime Env: Executes code (e.g., [Link]: V8 engine, event loop). One language
can have multiple (e.g., JS: Node, Deno, Bun).
• Framework: Builds on runtime for structure (e.g., Express on Node). Multiple per
runtime (NestJS, Fastify).
• Key: Runtime = infrastructure (memory, I/O); Framework = tools/best practices
(routing, ORM).
[Link] vs [Link]
• [Link]: Runtime for server-side JS (event-driven, non-blocking).
• [Link]: Minimal framework on Node for web apps/APIs (routing, middleware).
Simplifies HTTP handling.
Client Side vs Browser Side Differences
• Client-Side: Code runs on user's device (JS in browser via <script>; handles UI
logic).
• Browser-Side: Subset of client; specific to browser env (DOM, window object). Vs
Node: No DOM, but shared JS syntax.
Section 5: [Link] Features
7 Main Features of [Link]
1. Single-Threaded: One thread for JS; libuv for I/O.
2. Asynchronous: Non-blocking I/O (callbacks/promises).
3. V8 JS Engine: Fast execution (Google's engine).
4. Event-Driven: Responds to events via EventEmitter.
CORPORATE
5. Cross-Platform: Runs on Windows/Linux/macOS.
6. NPM: Package manager (2M+ packages).
7. Real-Time: WebSockets for interactive apps (chat, gaming).
What is Single-Threaded Programming?
Executes one task at a time on a single thread. Node uses this for JS, offloading I/O to thread
pool.
What is Synchronous Programming?
Tasks execute sequentially, blocking until complete (e.g., [Link]()). Slow for I/O.
Single-Threaded vs Synchronous Programming
• Single-threaded: Architecture (one JS thread).
• Synchronous: Execution style (blocking).
• Node: Single-threaded + async = efficient (handle many reqs without threads).
Sync vs Async Programming Differences
Sync Async
Blocking (waits) Non-blocking (continues)
Simple, error-prone for I/O Callbacks/promises; scalable
E.g., readFileSync E.g., readFile with callback
Event, Event Loop, Event Emitters, Event Queue, Event Handler
• Event: Action (e.g., 'data' on stream).
• Event Loop: Manages async ops (phases: timers, I/O, check). Processes queue.
• EventEmitter: Class to emit/listen events.
• Event Queue: Microtask (promises) + macrotask (timers) queues.
• Event Handler: Function attached via on().
Event-Driven Architecture
Components communicate via events (pub-sub). Advantages: Loose coupling, scalability.
Advantages of Node (Relate to Features)
• Fast I/O (async + event-driven).
• Scalable (single-thread handles 1000s reqs).
• Rich ecosystem (NPM).
• Real-time (WebSockets).
Disadvantages of Node
• CPU-intensive tasks block event loop (e.g., crypto hashing; use workers).
CORPORATE
• Callback hell (mitigated by promises).
• Not for multithread-heavy apps (use Go/Java).
What is a Module?
Reusable code block. Each .js file is a module (IIFE-wrapped). Good practice: Single
responsibility.
How to Export a Module
• CommonJS: [Link] = myFunc; or [Link] = () => {}; (alias, but
reassign carefully).
• ES Modules: export default myFunc; export { other }; (use "type": "module" in
[Link]).
How to Export Multiple Functions
javascript
// [Link]
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
[Link] = { add, subtract };
// Use: const { add } = require('./utils');
Types of Modules in [Link]
1. Built-in: Core (fs, http, path, os, events).
2. Local: Your files (require('./myfile')).
3. Third-Party: NPM installs (e.g., express).
FS Module Main Functions
From fs (file system):
• readFile(path, callback): Async read.
• writeFile(path, data, callback): Write/overwrite.
• appendFile(path, data, callback): Append.
• unlink(path, callback): Delete file.
• readdir(path, callback): List dir contents.
• mkdir(path, callback): Create dir.
• rmdir(path, callback): Remove dir (empty only; use rm for recursive).
Sync versions: readFileSync, etc.
Path Module in Detail
CORPORATE
Utilities for file paths (cross-platform):
• [Link]('/home', 'user', '[Link]'): '/' + 'user/[Link]' (uses OS separator).
• [Link]('/home', '[Link]'): Absolute path (/home/[Link]).
• [Link]('/path/to/[Link]'): '/path/to'.
• [Link]('[Link]'): '.txt'.
• [Link]('/[Link]'): '[Link]'.
Explain OS Module
os for OS interactions:
• [Link](): 'Darwin' (macOS), 'Linux'.
• [Link](): { uid, gid, username, homedir }.
• [Link]() / [Link](): Memory in bytes.
• [Link](): CPU info array.
• Use: Monitor server resources in production.
Event Implementation
See EventEmitter above. Example:
javascript
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
[Link]('greet', (name) => [Link](`Hello ${name}`));
[Link]('greet', 'World'); // Hello World
Function vs Event
• Function: Reusable code block, called directly.
• Event: Trigger for response; internally calls functions (handlers). Events decouple
(one-to-many).
HTTP Module in Node
Core for servers/clients. No framework needed.
javascript
const http = require('http');
const server = [Link]((req, res) => {
[Link](200, { 'Content-Type': 'text/plain' });
[Link]('Hello World');
});
[Link](3000, () => [Link]('Server running'));
CORPORATE
• createServer(): Callback for req/res.
Deployment, Load Balancing
• Deployment: PM2 (pm2 start [Link] --name myapp), Docker, Heroku/Vercel.
• Load Balancing: Nginx/HAProxy proxies reqs; Node cluster module for multi-core.
javascript
const cluster = require('cluster');
if ([Link]) {
for (let i = 0; i < [Link]().length; i++) [Link]();
} else require('./app');
Section 6: General Node Topics
Write Queries / Design Database Schema / SQL vs NoSQL
• SQL (Relational): Tables, joins, ACID (e.g., PostgreSQL for banking). Schema:
CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50));.
• NoSQL (Document): Flexible schemas, eventual consistency (MongoDB for e-
commerce). Schema: Collections like { users: [{ _id, name }] }.
• Diff: SQL for structured/transactions; NoSQL for scale/unstructured.
Query Optimizing Tool
• Indexing: Unique indexes speed lookups (e.g., Mongo: [Link]({ email:
1 }, { unique: true })).
• Tools: EXPLAIN in SQL, Mongo Profiler.
Create Promise: Return True When Resolves, False When Rejected; Use
Async/Await
javascript
function myPromise(success) {
return new Promise((resolve, reject) => {
if (success) resolve(true);
else reject(false);
});
}
// Async/Await
async function check() {
try {
CORPORATE
const result = await myPromise(true);
[Link](result); // true
} catch (err) {
[Link](err); // false
}
}
GET and POST Difference
• GET: Idempotent, for retrieval (query params, cacheable, visible in URL). E.g.,
/search?q=term.
• POST: For creation/mutation (body data, not cached, secure). E.g., form submit.
Package for Sending Mail
Nodemailer:
javascript
const nodemailer = require('nodemailer');
const transporter = [Link]({ service: 'gmail', auth:
{ user: 'email', pass: 'apppass' } });
[Link]({ to: 'user@[Link]', subject: 'Hi', text: 'Hello'
});
How to Connect DB to [Link]
Use Mongoose for Mongo:
javascript
const mongoose = require('mongoose');
[Link]('mongodb://localhost:27017/mydb')
.then(() => [Link]('Connected'))
.catch(err => [Link](err));
Handle Env Variables in [Link]
dotenv: npm i dotenv.
javascript
require('dotenv').config();
[Link]([Link].DB_URL); // From .env: DB_URL=mongodb://...
How to Decrypt Password in [Link]
CORPORATE
Don't decrypt—use one-way hashing (bcrypt). Compare hashes:
javascript
const bcrypt = require('bcrypt');
const hashed = await [Link]('password', 10);
const match = await [Link]('password', hashed); // true
Explain Folder Structure of [Link]
Typical:
text
project/
├── src/ # Source code
│ ├── controllers/ # Route handlers
│ ├── models/ # DB schemas
│ ├── routes/ # Express routes
│ └── [Link] # Main app
├── tests/ # Jest tests
├── .env # Secrets
├── [Link] # Deps/scripts
└── [Link]
What is EJS in [Link]
Embedded JavaScript: Templating engine (like Pug). Render HTML with JS:
javascript
[Link]('view engine', 'ejs');
[Link]('/', (req, res) => [Link]('index', { title: 'Home' })); //
views/[Link]: <h1><%= title %></h1>
Diff B/W Query Params and Request Params
• Query Params: After ? (e.g., /users?age=25; [Link]; for filtering).
• Request Params: In path (e.g., /users/123; [Link]; for specific resources).
Google Authentication: Use [Link]
javascript
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
CORPORATE
[Link](new GoogleStrategy({
clientID: [Link].GOOGLE_ID,
clientSecret: [Link].GOOGLE_SECRET,
callbackURL: '/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
// Save user to DB
return done(null, profile);
}));
[Link]('/auth/google', [Link]('google'));
[Link]('/auth/google/callback', [Link]('google'), (req,
res) => [Link]('/'));
What is WebSocket in [Link]? Explain Implementation
Bi-directional real-time comm (vs HTTP's request-response). [Link]:
javascript
const io = require('[Link]')(server);
[Link]('connection', (socket) => {
[Link]('chat', (msg) => [Link]('chat', msg)); // Broadcast
});
• Client: <script src="/[Link]/[Link]"></script>; [Link]('chat', 'Hi');
How to Manage Session in [Link]
express-session:
javascript
const session = require('express-session');
[Link](session({ secret: 'key', resave: false, saveUninitialized: true,
cookie: { maxAge: 60000 } }));
[Link]('/set', (req, res) => { [Link] = 'John'; });
[Link]('/get', (req, res) => [Link]([Link]));
How to Create DB Model in Node
With Mongoose:
javascript
const mongoose = require('mongoose');
CORPORATE
const userSchema = new [Link]({ name: String, email: { type:
String, unique: true } });
const User = [Link]('User', userSchema);
const newUser = new User({ name: 'John' }); [Link]();
Why Use Mongoose and Not Core MongoDB?
Mongoose adds schemas, validation, ODM ease; core is low-level (manual queries).
What is Cluster in [Link]
Multi-process for multi-core (bypasses single-thread limit). See deployment above.
Search Method in MongoDB, Regular Expression for Search
• Regex: [Link]({ name: { $regex: 'John', $options: 'i' } }) (case-insensitive).
• Text Search: Create index [Link]({ name: "text" }); query { $text: {
$search: "John" } }.
Task: Implement Authentication and Authorization
See JWT example above. Add roles: In middleware, if ([Link] !== 'admin') return 403;.
E-commerce Scenario: Access User Cart/Orders, Join Collections
Use Mongoose populate:
javascript
const userSchema = new [Link]({ name: String });
const cartSchema = new [Link]({ userId: { type:
[Link], ref: 'User' }, items: [] });
const Cart = [Link]('Cart', cartSchema);
[Link](userId).populate('carts').exec(); // Joins via ref
• Populate: Replaces IDs with docs.
How to Perform Search, Sort, Filter, Pagination in One API
javascript
[Link]('/products', async (req, res) => {
const { search, category, page = 1, limit = 10, sort = 'name' } =
[Link];
let query = { name: { $regex: search || '', $options: 'i' } };
if (category) [Link] = category;
CORPORATE
const products = await [Link](query)
.sort({ [sort]: 1 })
.limit(limit * 1)
.skip((page - 1) * limit);
[Link](products);
});
[Link] Microservices Architecture
Services communicate via REST/gRPC/RabbitMQ. Use Docker/K8s for orchestration.
Benefits: Scalable, fault-isolated.
How to Do Social Login (Google, Facebook) in Node? Same API for
Web/Android/iOS
Use [Link] (above for Google). Expose REST endpoints (e.g., /auth/google). Clients
(web/mobile) redirect to your API; use SDKs (Google Sign-In for Android/iOS). Same
backend handles all via tokens.
How to Integrate Payment Gateway in Node (e.g., Stripe)
Stripe:
javascript
const stripe = require('stripe')('sk_key');
[Link]('/charge', async (req, res) => {
const { amount, token } = [Link];
const charge = await [Link]({ amount, currency: 'usd',
source: token });
[Link](charge);
});
• Webhook for confirmations.
If Consumer Payment, Server Knows Internet Cut?
Use timeouts/retries in client SDK. Server: Webhooks from gateway (e.g., Stripe
'payment_intent.payment_failed'). Poll status if needed.
Explain How to Work with Chat Application
Use [Link] (above). Rooms for groups: [Link]('room1'); [Link]('room1').emit('msg',
data);. Store messages in Mongo.
CORPORATE
How to Secure [Link] Application
• HTTPS (Let's Encrypt).
• Helmet: [Link](helmet()); (security headers).
• Rate-limiting, input validation (Joi), bcrypt for pwds.
• CORS: [Link](cors({ origin: '[Link]' }));.
• Env secrets, audit logs.
How to Implement Push Notification in [Link]
FCM (Firebase):
javascript
const admin = require('firebase-admin');
[Link]({ credential: [Link]() });
[Link]().send({ token: 'deviceToken', notification: { title: 'Hi'
} });
Integrate with [Link] for real-time trigger.
Multiple Users (Admin, Consumer, Manager): How to Handle in [Link]
RBAC: Middleware checks roles from JWT. E.g., separate routes: /admin/* with admin
authz.
Email Send Implementation in [Link]
See Nodemailer above.
Multiple Email Upload Functionality in [Link]
Multer for files:
javascript
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
[Link]('/emails', [Link]('emails', 10), (req, res) => {
[Link](file => { /* Process each */ });
});
Limit size: { limits: { fileSize: 5 * 1024 * 1024 } }.
If I Want to Upload 3GB File, How Handled in [Link]?
Stream it: Use multer with diskStorage or busboy. Chunk uploads (e.g., [Link] client).
Node streams prevent memory overload. Set maxFileSize high; use S3 for storage.
CORPORATE
How Can You Encrypt Your Password in [Link]
Use bcrypt (one-way): See above.
Forgot Password Functionality in [Link]
1. User emails token (JWT with reset flag, short expiry).
2. API: /forgot generates/sends token via email.
3. /reset/:token: Verify token, update pw (hash new one).
CORS in [Link]
Cross-Origin Resource Sharing: Allow domains.
javascript
const cors = require('cors');
[Link](cors({ origin: '[Link] credentials: true }));
How to Create [Link] Server Without Using [Link]
See HTTP module above.
How to Do Pagination in [Link]
See search/sort example above (skip/limit).
How to Optimize Your Search Query
• Indexing on search fields.
• Limit results, use projections (select: { name: 1 }).
• Aggregation for complex; cache with Redis.
Section 7: Real-World Scenario-Based Questions
Prepare Real-World Scenario-Based Questions
1. Scenario: High-Traffic E-commerce Site Crashing on Black Friday. How
optimize? Answer: Cluster for multi-core, Redis cache, DB indexing/sharding, CDN
for statics, monitor with PM2. Rate-limit endpoints.
2. Scenario: User Reports Slow API Response. Debug steps? Answer: Profile with
[Link], check DB queries (explain), add logging/timers. Optimize bottlenecks (e.g.,
N+1 queries with populate).
3. Scenario: Secure User Data in Banking App. Implement authz? Answer: JWT +
RBAC middleware; encrypt sensitive fields (crypto); audit logs; comply with PCI-
DSS.
CORPORATE
4. Scenario: Real-Time Stock Updates. Architecture? Answer: [Link] for push;
pub-sub (Redis) for scaling; fallback to polling.
5. Scenario: Migrate Monolith to Microservices. Steps? Answer: Identify services,
Dockerize, K8s orchestrate, API gateway (Kong), service mesh (Istio) for comms.
How to Optimize [Link] Apps
• Clustering/workers for CPU.
• Caching (Redis).
• DB optimization (indexes, connection pooling).
• Compress responses (compression middleware).
• Profile: --inspect + Chrome DevTools.
[Link] and setImmediate
• [Link](fn): Queues fn after current op, before I/O (microtask, highest
priority).
• setImmediate(fn): Queues after current poll phase (macrotask).
• Diff: nextTick for immediate (can starve loop); setImmediate for I/O-balanced.
Real-Time Communication in [Link]
WebSockets/[Link] (above). For scale: Use Redis adapter for multi-server.
Worker Thread in [Link]
For CPU tasks:
javascript
const { Worker, isMainThread, parentPort, workerData } =
require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename, { workerData: { num: 10 } });
[Link]('message', msg => [Link](msg));
} else {
// Heavy compute
[Link]({ result: [Link] * 2 });
}
Which Architecture Preferable for Building App Using [Link]
Microservices for large/scale (independent deploys); Monolith for small/fast dev. Hybrid:
Modular monolith first.
Write Code for Creating Server Without/With [Link]
CORPORATE
Without (HTTP): See above. With Express:
javascript
const express = require('express');
const app = express();
[Link]('/', (req, res) => [Link]('Hello'));
[Link](3000);
File System Module in [Link]
See FS above.
Which DB Using with [Link] and Write Code (Use Sequelize)
PostgreSQL with Sequelize (ORM):
javascript
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('postgres://user:pass@localhost:5432/db');
const User = [Link]('User', {
name: [Link]
});
await [Link]();
await [Link]({ name: 'John' });
Implement Authentication in [Link]
See JWT example.
Section 8: JavaScript Topics
Deep Copy vs Shallow Copy
• Shallow: Copies refs (nested objects shared). E.g., [Link]({}, obj).
• Deep: Recursively copies all. E.g., [Link]([Link](obj)) or lodash
_.cloneDeep().
• When: Deep for independent mutations.
Generator Functions in JS
Yield values lazily:
javascript
CORPORATE
function* gen() {
yield 1;
yield 2;
}
const iterator = gen();
[Link]([Link]().value); // 1
• Use: Infinite sequences, async iterators.
Call, Apply, Bind
Bind context (this):
javascript
const obj = { name: 'John' };
function greet(greeting) { return `${greeting} ${[Link]}`; }
[Link]([Link](obj, 'Hi')); // Hi John (call: args separate)
[Link]([Link](obj, ['Hi'])); // Hi John (apply: args array)
const bound = [Link](obj); [Link](bound('Hi')); // Hi John
Task: Take a String and Return Object with Character Counts
javascript
function countChars(str) {
const count = {};
for (let char of str) {
count[char] = (count[char] || 0) + 1;
}
return count;
}
[Link](countChars('hello')); // { h:1, e:1, l:2, o:1 }