NodeJS Interview Docs
NodeJS Interview Docs
Event Loop:
The event loop is a core concept in Node.js that enables non-blocking,
asynchronous programming. It is the mechanism that handles multiple
operations concurrently, allowing Node.js to execute JavaScript code, perform
I/O operations, and manage other tasks without blocking the main thread.
Single-Threaded Nature:
Pending Callbacks: Handles I/O callbacks that were deferred from the
previous cycle.
Poll: This is the most important phase, where the event loop waits for
new I/O events, executes callbacks for completed I/O operations, and
handles other events.
When Node.js starts, it initializes the event loop and begins executing
JavaScript code.
The event loop checks the queue and, when it reaches the appropriate
phase, it executes the queued callback.
Example:
Asynchronous programming:
Asynchronous programming in JavaScript, especially in Node.js, allows
operations to be executed without blocking the main thread. This means that
tasks like reading files, making network requests, or performing database
queries can be performed in the background while the main program continues
executing. This is crucial for building scalable applications where multiple I/O
operations need to be handled efficiently.
Example:
Example:
Buffers allow you to interact with raw memory directly, which is not possible
with standard JavaScript data types like strings.
Example:
process.
asynchronous operations.
Example:
Types of Modules:
1. Core Modules: Built into Node.js (e.g., fs , http , path ).
Example:
Calls the add and multiply functions and logs their results.
Middleware:
Middleware in Node.js, especially when using frameworks like Express.js,
refers to functions that have access to the request ( req ) and response ( res )
objects, as well as the next function in the application's request-response
cycle. Middleware functions can perform operations on the request object,
modify the response, end the request-response cycle, or call the next
middleware in the stack.
Types of Middleware:
1. Application-level Middleware: Applies to all routes or specific routes.
Routing:
Routing in Node.js, especially when using a framework like Express.js, refers
to defining the various endpoints of your web server and specifying how it
should respond to client requests. Each route can be associated with a specific
HTTP method (like GET, POST, PUT, DELETE) and a URL path. This allows you
to create RESTful APIs or serve different content based on the requested path.
2. Route Path: Defines the path that the server listens to. For example, / ,
/users , or /products/:id .
3. Route Handler: A function that defines what should happen when a request
matches a specified path and method.
Example:
Error Handling:
Error Handling is essential for ensuring that your application can gracefully
handle unexpected situations, such as failed database queries, file read/write
errors, network issues, and more. It allows the application to respond to errors
3. Promise .catch() Method: Used for handling errors when working with
Promises.
Example:
Explanation:
Middleware:
GET Route:
Logs the request method ( GET ) and URL ( / ) using req.method and
req.url .
POST Route:
Extracts name and email from req.body and sends back a JSON
response using res.json() .
For example, even after logging in, a user may only be allowed to view
their own profile and not that of another user.
Example:
2. Uniform Interface: Uses standard HTTP methods and status codes for
consistency.
Example:
GET /users/:id :
Searches for the user and returns a 404 status if not found.
POST /users :
Adds a new user to the users array and assigns a new ID.
PUT /users/:id :
DELETE /users/:id :
Responds with a 204 status code indicating that the resource was
successfully deleted without returning any content.
API Security:
API Security in Node.js involves safeguarding the APIs from malicious attacks,
unauthorized access, data breaches, and other vulnerabilities. It ensures that
only authenticated and authorized clients can interact with the API, and that the
data transmitted remains secure. This is especially crucial when building APIs
that handle sensitive information like user data, payments, or personal details.
5. Input Validation: Ensuring that the data being sent to the API is properly
formatted and does not contain harmful content (e.g., SQL injection or XSS
attacks).
Rate Limiting:
JWT Authentication:
Uses JWT for user authentication, allowing users to obtain a token upon
successful login.
2. Validate Input: Sanitize and validate user input to prevent SQL injection,
XSS, and other attacks.
3. Use Strong Secrets for JWT: Use a strong secret key for signing JWTs and
store it securely (e.g., in environment variables).
Data Validation:
The process of ensuring that the data sent by users or clients to the server is
accurate, formatted correctly, and meets the required criteria before it is
processed or stored. This is critical for maintaining data integrity, ensuring that
Example:
Joi Validation
Uses the validate() method to check if the input matches the schema.
If the validation fails, it extracts the error message and responds with a
400 status code.
Websocket:
WebSockets are a communication protocol that enables full-duplex (two-way)
communication between a client and a server over a single, long-lived
connection. Unlike traditional HTTP requests, which require the client to initiate
every interaction, WebSockets allow for real-time data transfer, making them
ideal for applications such as chat apps, live notifications, online gaming, and
collaborative tools.
Features of WebSockets:
WebSocket Security:
1. Use of WSS: Always use the secure version of WebSocket ( wss:// ) to
encrypt data in transit, preventing eavesdropping and man-in-the-middle
attacks.
5. Input Validation: Always validate and sanitize input data received through
WebSocket messages to prevent injection attacks.
3. Custom Events: You can create and emit custom events, tailoring the event
handling to the specific needs of your application.
Basic Terminology:
Emitter: An object that emits events.
How It Works:
1. You create an instance of the EventEmitter class.
Example:
Features of Clustering:
1. Load Balancing: Clustering helps distribute the incoming traffic across
multiple instances, reducing the load on a single instance and improving
overall performance.
2. Each worker process listens for incoming requests and handles them
independently.
3. The master process can also be used to monitor the health of worker
processes and restart them if necessary.
Example:
Explanation:
Master Process:
The master process listens for exit events from workers and logs when
a worker dies.
Worker Processes:
Each worker listens for incoming requests on the same port (8000),
allowing them to share the same TCP connection.
Caching:
Caching is a technique used to store frequently accessed data in memory to
improve performance and reduce latency when serving requests. By caching
data, you can avoid redundant calculations, database queries, or network
requests, resulting in faster response times and a more efficient application.
Types of Caching:
1. In-Memory Caching: Stores data in the server's memory (e.g., using
packages like node-cache or redis ).
Example:
2. Least Connections: Sends requests to the server with the fewest active
connections.
Memory Management:
The process of efficiently allocating, using, and deallocating memory resources
in a Node.js application. Proper memory management is crucial for maintaining
performance, preventing memory leaks, and ensuring the stability of
applications, especially those that handle a large number of concurrent
requests.
Importance:
Heap and Stack Memory: Node.js uses both heap memory (for dynamic
memory allocation) and stack memory (for function calls and local
2. Weak References: Utilize weak references for objects that can be garbage
collected if there are no strong references to them. This can help prevent
memory leaks.
3. Avoiding Global Variables: Global variables can lead to memory leaks since
they persist for the entire lifetime of the application.
4. Profiling Memory Usage: Use tools like Chrome DevTools, Node.js built-in
profiling, or third-party modules like clinic.js to monitor and analyze
memory usage.
Example:
1. Node.js Debugger: Use the built-in debugger to step through your code
and analyze memory allocation.
Best Practices:
1. Minimize Global Variables: Use local variables and encapsulation to limit
the scope of memory usage.