Node.js Interview Questions (50+ Detailed Q&A)
1. Runtime & Core Architecture
1. What is Node.js? Is it a framework?
1. What is Node.js? Is it a framework?
2. Single Threaded but Scalable? How?
2. Single Threaded but Scalable? How?
3. Event Loop Phases (Deep Dive)
3. Event Loop Phases (Deep Dive)
- Timers:
setTimeout,setInterval. - Pending Callbacks: OS system errors.
- Idle/Prepare: Internal.
- Poll: Retrieve new I/O events, execute I/O callbacks. (Main phase).
- Check:
setImmediate. - Close Callbacks:
socket.on('close'). Microtasks (nextTick, Promises) run between phases.
setImmediate runs first.4. `process.nextTick` vs `setImmediate`
4. `process.nextTick` vs `setImmediate`
nextTick: Runs immediately after current operation, before the loop continues. (Starvation risk).setImmediate: Runs in the Check phase (next tick of the loop technically).
nextTick: When you need to execute before ANY I/O (e.g., emit events after constructor)setImmediate: When you want to execute after I/O events (preferred for recursion)
5. V8 Engine Memory Limit
5. V8 Engine Memory Limit
node --max-old-space-size=4096 app.js.6. Garbage Collection in Node
6. Garbage Collection in Node
- Scavenge: Minor GC (New Space). Fast. Moves live objects to Old Space.
- Mark-Sweep-Compact: Major GC (Old Space). Stops execution.
7. Global Objects
7. Global Objects
global, process, Buffer, __dirname (Module scope), __filename, require, module.
(Window is not available).8. CommonJS vs ESM
8. CommonJS vs ESM
- CJS:
require(). Sync. Dynamic.module.exports. - ESM:
import. Async. Static.export default.
9. `exports` vs `module.exports`
9. `exports` vs `module.exports`
exports is a reference to module.exports.
exports.a = 1 works.
exports = { a: 1 } BREAKS the link. Always use module.exports if assigning object.10. Handling CPU Intensive Tasks
10. Handling CPU Intensive Tasks
- Worker Threads (Parallel execution).
- Child Process (Fork new process).
- Offload to other service (Go/Rust/Queue).
2. Streams, Buffers, I/O
11. What is a Buffer?
11. What is a Buffer?
Buffer.from('hello').12. Streams: 4 Types
12. Streams: 4 Types
- Readable:
fs.createReadStream. - Writable:
res(Response),fs.createWriteStream. - Duplex: Sockets (Read/Write).
- Transform: Zlib (Compress), Crypto. (Modify data passing through).
13. Pipe & Backpressure
13. Pipe & Backpressure
read.pipe(write) handles this automatically (Pauses read until write drains).14. `fs.readFile` vs `fs.createReadStream`
14. `fs.readFile` vs `fs.createReadStream`
readFile: Loads entire file into RAM (Buffer). Crashes on large files.readStream: Reads in Chunks. Memory efficient. Constant RAM usage regardless of file size.
15. Event Emitter Pattern
15. Event Emitter Pattern
events module. Pub/Sub.
const e = new EventEmitter();
e.on('event', cb);
e.emit('event', data).
Node streams/server inherit from this.16. Handling uncaught exceptions
16. Handling uncaught exceptions
process.on('uncaughtException').
Best Practice: Log error and Restart Process (State might be corrupted).
process.on('unhandledRejection') for Promises.17. Synchronous vs Asynchronous API
17. Synchronous vs Asynchronous API
fs.readFileSync blocks the thread.
Only use Sync methods at Startup (config loading). Never in Request Handler.18. Zlib and Compression
18. Zlib and Compression
src.pipe(zlib.createGzip()).pipe(dest).19. REPL
19. REPL
20. OS Module
20. OS Module
os.cpus(), os.freemem(), os.networkInterfaces().
Used for Cluster setup or monitoring.3. Web & Network (HTTP/Express)
21. Anatomy of HTTP Server
21. Anatomy of HTTP Server
http.createServer((req, res) => ...)
req: Readable Stream (Incoming data).
res: Writable Stream (Outgoing data).22. Middleware (Express)
22. Middleware (Express)
req, res, next.
Chain of responsibility.
Global (app.use) or Route specific.
Calls next() to pass control.23. Error Handling Middleware
23. Error Handling Middleware
(err, req, res, next).
Express recognizes arity.
Placed at the end of the stack.24. Body Parsing
24. Body Parsing
data events on req stream and concatenate.
Express: express.json() middleware. Parsing JSON/URL-encoded bodies.25. CORS in Node
25. CORS in Node
Access-Control-Allow-Origin.
Middleware: cors package.
Handle OPTIONS preflight requests.26. JWT (JSON Web Token)
26. JWT (JSON Web Token)
jwt.verify(token, secret).27. Cookies vs Sessions
27. Cookies vs Sessions
28. File Uploads
28. File Uploads
busbody) or Middleware (multer).
Handle multipart/form-data.
Don’t save to Disk in serverless. Stream to S3.29. WebSockets (`socket.io`)
29. WebSockets (`socket.io`)
30. Keep-Alive Agent
30. Keep-Alive Agent
http.Agent({ keepAlive: true }) to reuse connections (Connection Pooling).4. Scaling & Performance
31. Cluster Module
31. Cluster Module
32. PM2 Process Manager
32. PM2 Process Manager
-i max), Logs, Monitoring.33. Worker Threads
33. Worker Threads
34. Memory Leaks Causes
34. Memory Leaks Causes
- Global variables.
- Unclosed Event Listeners (adding listener on every req).
- Closures holding large objects.
- Cache without TTL.
35. N+1 Problem (GraphQL/ORM)
35. N+1 Problem (GraphQL/ORM)
36. Database Connection Pooling
36. Database Connection Pooling
pg.Pool or Mongoose built-in pool.37. Caching Strategies
37. Caching Strategies
- In-Memory (Node): Fast, but clears on restart, duplicates RAM in cluster.
- Distributed (Redis): Shared, Persistent, Fast.
38. Profiling Node App
38. Profiling Node App
--inspect. Chrome DevTools.
Flame Graphs (0x, Clinic.js). shows CPU time per function.39. Event Loop Block Loophole
39. Event Loop Block Loophole
JSON.parse or JSON.stringify on massive objects blocks the loop.
Regex DoD (Denial of Service).40. Microservices Communication
40. Microservices Communication
- HTTP/REST: Simple, slow (JSON).
- gRPC: Protobuf (Binary), fast, strict contract.
- Message Queues (RabbitMQ/Kafka): Async, Decoupled.
5. Security & Testing
41. SQL Injection & NoSQL Injection
41. SQL Injection & NoSQL Injection
- SQL: User input concatenating query. Fix: Prepared Statements.
- NoSQL: Mongo query
{ username: req.body.user }. If user sends{"$ne": null}, they bypass login. Fix: Sanitize input.
42. XSS (Cross Site Scripting)
42. XSS (Cross Site Scripting)
43. CSRF (Cross Site Request Forgery)
43. CSRF (Cross Site Request Forgery)
44. Helmet.js
44. Helmet.js
45. Rate Limiting
45. Rate Limiting
express-rate-limit (Memory/Redis).
Strategies: Fixed Window, Token Bucket.46. Unit Testing (Jest/Mocha)
46. Unit Testing (Jest/Mocha)
47. Dependency Injection
47. Dependency Injection
class Service { constructor(db) ... }48. TDD (Test Driven Development)
48. TDD (Test Driven Development)
49. Environment Variables
49. Environment Variables
.env files. dotenv package.
Separates Config from Code. Secrets (API Keys) should never be in git.50. Logging Best Practices
50. Logging Best Practices
console.log (Sync, blocking in TTY).
Use Logger (Winston/Pino) -> JSON output -> Stdout.
Log Levels (Info, Error, Debug).
Correlation IDs for tracing.6. Node.js Medium Level Questions
51. Express Middleware Order
51. Express Middleware Order
52. Route Parameters and Query Strings
52. Route Parameters and Query Strings
53. Body Parsing
53. Body Parsing
54. Cookie and Session Management
54. Cookie and Session Management
55. Error Handling in Express
55. Error Handling in Express
56. CORS Configuration
56. CORS Configuration
57. Rate Limiting
57. Rate Limiting
58. Input Validation
58. Input Validation
59. Database Connection Pooling
59. Database Connection Pooling
60. MongoDB with Mongoose
60. MongoDB with Mongoose
61. JWT Authentication
61. JWT Authentication
62. Password Hashing with bcrypt
62. Password Hashing with bcrypt
63. File Uploads with Multer
63. File Uploads with Multer
64. Email Sending with Nodemailer
64. Email Sending with Nodemailer
65. Testing with Jest
65. Testing with Jest
66. Mocking with Jest
66. Mocking with Jest
67. Environment Variables
67. Environment Variables
68. Logging with Winston
68. Logging with Winston
69. HTTP Request Logging
69. HTTP Request Logging
70. Static File Serving
70. Static File Serving
7. Node.js Advanced Level Questions
71. Custom Stream Implementation
71. Custom Stream Implementation
72. Transform Streams
72. Transform Streams
73. Backpressure Handling
73. Backpressure Handling
74. Child Processes
74. Child Processes
75. Cluster Module
75. Cluster Module
76. Worker Threads
76. Worker Threads
77. Performance Hooks
77. Performance Hooks
78. Heap Snapshots
78. Heap Snapshots
79. CPU Profiling
79. CPU Profiling
80. HTTP/2 Server
80. HTTP/2 Server
81. WebSocket Server
81. WebSocket Server
82. GraphQL Server
82. GraphQL Server
83. Message Queues with RabbitMQ
83. Message Queues with RabbitMQ
84. Redis Caching
84. Redis Caching
85. Graceful Shutdown
85. Graceful Shutdown
86. Health Checks
86. Health Checks
87. Request Timeout Handling
87. Request Timeout Handling
88. Memory Leak Detection
88. Memory Leak Detection
89. Native Addons with N-API
89. Native Addons with N-API
90. Microservices Communication
90. Microservices Communication