Node.
js Interview Preparation Notes
1. Node.js Fundamentals
What is Node.js?
Node.js is a runtime environment that allows JavaScript to run outside of the
browser. It is built on Google Chrome's V8 JavaScript engine and uses an event-
driven, non-blocking I/O model, making it efficient for scalable network applications.
Key Features of Node.js
● Single-threaded & Asynchronous → Uses event loops and callbacks.
● Non-blocking I/O → Handles multiple operations without waiting.
● Fast Execution → Runs JavaScript code quickly using the V8 engine.
● Cross-platform → Runs on Windows, macOS, and Linux.
● Built-in Modules → Provides modules like fs (file system), http, path, etc.
Example: Creating a Basic HTTP Server
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');
});
2. Promises and Async/Await
Promises
A Promise is an object that represents a value that might be available now, later, or
never. It has three states:
● Pending → Initial state.
● Resolved (Fulfilled) → Operation successful.
● Rejected → Operation failed.
Example: Using Promises
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data received!'), 2000);
});
};
fetchData().then(console.log).catch(console.error);
Async/Await
Async/Await is a more readable way to handle asynchronous operations instead of
chaining .then().
Example: Using Async/Await
const fetchData = async () => {
try {
let data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
};
fetchData();
3. Error Handling in Node.js
Types of Errors
1. Operational Errors (e.g., file not found, failed network requests).
2. Programming Errors (e.g., syntax errors, undefined variables).
Error Handling with Try-Catch
try {
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
}
Handling Errors in Async Functions
const fetchData = async () => {
try {
let data = await fetchData();
console.log(data);
} catch (error) {
console.error('Error:', error.message);
}
};
4. API Security
● Rate Limiting → Limit the number of requests per user (e.g., using express-
rate-limit).
● Input Validation → Use libraries like Joi or express-validator.
● CORS Protection → Restrict API access from unknown domains.
● Data Encryption → Encrypt sensitive data using bcrypt or crypto.
5. Database Performance (Indexing,
Scaling, Pagination)
Indexing
Indexes speed up database queries by allowing fast lookups.
CREATE INDEX idx_name ON users(name);
Scaling
● Vertical Scaling → Increasing server resources (CPU, RAM).
● Horizontal Scaling → Adding more database servers.
Pagination
const getUsers = async (page, limit) => {
return await db.collection('users')
.find()
.skip((page - 1) * limit)
.limit(limit)
.toArray();
};
6. Authentication and Security (JWT and
OAuth)
JWT (JSON Web Token)
Used for secure authentication.
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
OAuth
OAuth is a protocol for secure authentication (e.g., Google Login, Facebook Login).
7. Caching with Redis
What is Redis?
Redis is an in-memory database that stores frequently accessed data to improve
speed.
Example: Using Redis in Node.js
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value', redis.print);
client.get('key', (err, reply) => console.log(reply));
8. Process Management (PM2)
What is PM2?
PM2 is a process manager for running Node.js applications in production.
Starting an App with PM2
pm install -g pm2
pm2 start app.js --name myApp
9. Version Control (Git and GitHub)
Git Commands
git init
git add .
git commit -m "Initial commit"
git push origin main
10. WebSockets and Streams
WebSockets (Real-time Communication)
WebSockets enable real-time, bi-directional communication between the client and
server.
Example: WebSocket Server in Node.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => {
ws.send('Welcome!');
ws.on('message', (message) => ws.send(`Received: ${message}`));
});
Streams (Efficient Data Handling)
Streams allow processing large files in chunks without consuming memory.
Example: Reading a File Stream
const fs = require('fs');
const readStream = fs.createReadStream('largeFile.txt', 'utf8');
readStream.on('data', (chunk) => console.log('Received:', chunk));
Conclusion
● Node.js is an efficient JavaScript runtime for building scalable applications.
● Async programming improves performance using Promises and async/await.
● API security ensures safe and secure applications.
● Databases need optimization through indexing, scaling, and pagination.
● Authentication via JWT/OAuth protects user data.
● Redis caching speeds up frequent requests.
● Process management via PM2 keeps applications running in production.
● Git/GitHub helps in version control.
● WebSockets and Streams enable real-time data processing.
This guide provides essential knowledge for your interview. Good luck! 🚀