Yo
ChatGPT said:
Here’s a list of advanced-level Node.js interview questions along with example scenarios, plus insights on how to create a secure and well-structured API using best practices:
Advanced Node.js Interview Questions with Example Scenarios
1. How does the Node.js event loop work?
Scenario:
Imagine a high-traffic API for stock trading. You need to ensure non-blocking I/O for processing requests in real-time.
Answer:
Node.js uses a single-threaded event loop model. Long-running tasks are delegated to worker threads or callbacks. Knowing the event loop phases (timers, I/O callbacks, idle, poll, check, close callbacks) helps in optimizing performance.
2. Explain Streams in Node.js with an example.
Scenario:
You need to build an endpoint to upload large video files without loading the entire file into memory.
Answer:
Use readable and writable streams. For example:
app.post('/upload', (req, res) => {
const writeStream = fs.createWriteStream('video.mp4');
req.pipe(writeStream);
req.on('end', () => res.send('Uploaded!'));
});
3. How do you handle concurrency in Node.js?
Scenario:
Multiple users trying to update the same resource at once (e.g., a shared document).
Answer:
Use atomic operations with the database, locking mechanisms (Redis, etc.), or use Node.js clusters or worker threads for CPU-bound tasks.
4. What is middleware in Express.js?
Scenario:
You need to log request data and check authentication before hitting the controller.
Answer:
Middleware functions run before hitting the final route.
jsapp.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
5. How to prevent memory leaks in a long-running Node.js process?
Scenario:
An API server keeps crashing after a few hours.
Answer:
Use tools like Node.js Inspector, heapdump
, clinic.js
. Check event listeners, clear timers, avoid global state pollution.
6. What are the best practices for API design in Node.js (Express)?
Best Practices to Create Secure Node.js API
1. Use HTTPS
Always serve APIs over HTTPS using certificates (Let’s Encrypt is free).
2. Input Validation and Sanitization
Use libraries like
Joi
,Zod
, orexpress-validator
to validate input.
jsconst { body, validationResult } = require('express-validator');
app.post('/user',
body('email').isEmail(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
// Safe to proceed
});
3. Authentication & Authorization
Use JWT or OAuth2.
Store passwords securely with
bcrypt
.
jsconst jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
4. Rate Limiting & Throttling
Use
express-rate-limit
to protect against brute force.
jsconst rateLimit = require("express-rate-limit");
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use(limiter);
5. Secure Headers
Use
helmet
to set various HTTP headers.
jsconst helmet = require('helmet');
app.use(helmet());
6. Prevent NoSQL Injection / SQL Injection
Sanitize all input, use parameterized queries.
7. Use Environment Variables
Never hardcode secrets. Use
.env
and access viaprocess.env
.
Folder Structure for Scalable API
project/ ├── controllers/ ├── routes/ ├── models/ ├── middlewares/ ├── utils/ ├── services/ ├── config/ ├── app.js └── server.js
Want me to generate a sample secure API code scaffold for you wit
No comments:
Post a Comment