1. What is Node.js?
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a web browser. It uses the V8 JavaScript engine, developed by Google, which compiles JavaScript directly into machine code, contributing to its exceptional performance and efficiency. It allows developers to run JavaScript on the server side, enabling the creation of scalable and efficient server-side applications.
Key Features of Node.js:
- Event-Driven Architecture: Efficient handling of I/O operations.
- Non-Blocking I/O Model: Prevents blocking operations, enhancing performance.
- Single-Threaded Event Loop: Handles multiple concurrent requests efficiently.
- Package Management: Managed via npm (Node Package Manager).
- Cross-Platform Compatibility: Runs on Windows, macOS, and Linux.
Example:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
}).listen(3000);
console.log('Server running at http://localhost:3000/');
2. Event Loop in Node.js
The Event Loop is a core concept in Node.js that handles asynchronous operations.
Key Points:
- It waits for tasks, executes them, and sleeps until more tasks arrive.
- Executes tasks from the Event Queue when the Call Stack is empty.
- Allows Node.js to handle thousands of concurrent connections efficiently.
Phases of Event Loop:
Below is a visual representation of the Event Loop phases to enhance clarity:
-
Timers Phase: Executes
setTimeout
andsetInterval
callbacks. - Pending Callbacks Phase: Handles I/O callbacks.
- Idle/Prepare Phase: Internal operations.
- Poll Phase: Retrieves new I/O events.
-
Check Phase: Executes
setImmediate()
callbacks. -
Close Callbacks Phase: Handles
close
events (e.g., socket.on('close')).
Example:
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
process.nextTick(() => console.log('NextTick'));
console.log('End');
Output:
Start
End
NextTick
Timeout
3. Why Node.js Instead of Other Frameworks?
- Asynchronous and Non-Blocking: Efficient in handling heavy I/O tasks.
- Single Programming Language: JavaScript for both frontend and backend.
- Lightweight: Consumes fewer system resources.
- Scalability: Suitable for real-time applications.
- Active Community: Extensive npm libraries.
Comparison with Traditional Web Servers:
- Traditional Servers: Multi-threaded, blocking operations.
- Node.js: Single-threaded, non-blocking I/O.
4. Clusters in Node.js
Node.js is single-threaded, but clusters allow it to utilize multiple CPU cores.
Key Points:
- Each cluster is a child process.
- Shares server ports among worker processes.
- Improves application scalability.
Example:
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} exited`);
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Hello from Worker ${process.pid}`);
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}
5. Authentication vs Authorization
- Authentication: Verifying the user’s identity (e.g., login credentials).
- Authorization: Verifying access rights to resources (e.g., Admin vs User privileges).
Example:
- Authentication: Validating username/password.
- Authorization: Checking if the user can access
/admin
route.
6. Middleware in Node.js
Middleware functions are functions executed during the request-response cycle.
Key Functions:
- Modify
req
andres
objects. - Execute code before passing control to the next middleware.
- End the request-response cycle.
Example:
app.use((req, res, next) => {
console.log('Middleware executed');
next();
});
7. JWT Algorithms
- JWTs use SHA-256 for hashing.
- RSA (asymmetric encryption) is used for signing.
8. Command Line Input (CLI)
Used for interacting with systems and tools without GUI.
Example:
node index.js --port=3000
9. NPM and Package Files
- npm: Package manager for Node.js.
- package.json: Project metadata.
- package-lock.json: Locks dependency versions.
10. Error Handling in Node.js
- Try-Catch: For synchronous code.
- Error Events: For async tasks.
- Promise.catch: For rejected promises.
Example:
try {
throw new Error('Something went wrong');
} catch (err) {
console.error(err.message);
}
11. Synchronous vs Asynchronous Code
- Synchronous: Blocking.
- Asynchronous: Non-blocking.
Example:
fs.readFile('file.txt', (err, data) => console.log(data));
console.log('This runs first');
12. Global Exception Handler
Handles uncaught exceptions to prevent application crashes.
Example:
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
});
13. MVC Architecture
- Model: Manages data and business logic.
- View: Responsible for the presentation layer (UI/UX).
- Controller: Handles user input and interacts with the model and view.
Key Benefits:
- Separation of concerns.
- Better scalability and maintainability.
- Easier debugging and testing.
Example Structure:
app/
├── models/
│ └── userModel.js
├── views/
│ └── userView.ejs
├── controllers/
│ └── userController.js
└── routes/
└── userRoutes.js
14. How would you define the term I/O?
I/O stands for Input/Output and refers to any operation that involves reading data from or writing data to an external resource, such as a file, database, or network.
In Node.js:
- Input: Data received from external sources (e.g., user requests, file system).
- Output: Data sent to external sources (e.g., API responses, file writes).
Example:
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
15. Explain Callback in Node.js
A callback is a function passed as an argument to another function, which gets executed once the asynchronous task is complete.
Key Points:
- Avoid blocking operations.
- Improve performance.
- Commonly used in asynchronous APIs.
Example:
fs.readFile('file.txt', (err, data) => {
if (err) console.error(err);
else console.log(data.toString());
});
This guide provides a professional overview of key Node.js concepts, useful for both interview preparation and real-world applications.
Author: Mohin Sheikh
Follow me on GitHub for more insights!
Top comments (0)