0% found this document useful (0 votes)
28 views

NodeJS Interview Docs

Uploaded by

Trọng Hoàng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

NodeJS Interview Docs

Uploaded by

Trọng Hoàng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Node JS Interview Topics:

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.

How the Event Loop Works


Node.js is built on the V8 JavaScript engine and the libuv library, which
provides the event loop. The event loop processes callbacks and handles
asynchronous operations like file I/O, network requests, timers, and more.

Single-Threaded Nature:

Node.js operates on a single thread for executing JavaScript code.


However, it handles I/O operations and other asynchronous tasks using
the event loop and a pool of threads (from libuv ).

While the JavaScript execution happens in a single thread, the event


loop allows Node.js to manage I/O operations without blocking this
thread.

Phases of the Event Loop:

Timers: This phase executes callbacks from setTimeout and setInterval

if their timers have expired.

Pending Callbacks: Handles I/O callbacks that were deferred from the
previous cycle.

Idle, Prepare: Internal operations for the event loop.

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.

Check: Executes callbacks from setImmediate() functions.

Close Callbacks: Executes callbacks for close events, such as when a


socket or handle is closed.

Node JS Interview Topics: 1


Execution Flow:

When Node.js starts, it initializes the event loop and begins executing
JavaScript code.

Synchronous code is executed first. Asynchronous operations (e.g., I/O


tasks, timers) are delegated to the libuv library, which manages them
outside the main thread.

When the asynchronous operations complete (e.g., a file is read or a


network request finishes), the relevant callback is added to a queue.

The event loop checks the queue and, when it reaches the appropriate
phase, it executes the queued callback.

Example:

Why is the Event Loop Important?

Non-blocking I/O: The event loop allows Node.js to perform non-


blocking I/O operations, making it suitable for building scalable
applications, especially for handling many connections or performing
I/O-intensive tasks.

Concurrency: Even though Node.js is single-threaded, the event loop


helps manage multiple tasks by deferring execution until the system is
ready to handle them, thus achieving concurrency.

Node JS Interview Topics: 2


Simplified Development: By abstracting the complexity of dealing with
multiple threads, the event loop makes it easier to write and manage
asynchronous code using callbacks, promises, or async/await .

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.

Asynchronous programming uses mechanisms like


callbacks, Promises, and async/await to handle operations
that may take time to complete, without freezing the entire
application.

Example:

Node JS Interview Topics: 3


Streams:
Streams are objects that allow you to read data from a source or write data to a
destination in a continuous fashion. They are a powerful way to handle I/O
operations because they enable processing data piece by piece rather than
waiting for the entire data to be available, which is especially useful for large
files or when working with network requests.

Types of Streams in Node.js:


1. Readable Streams: For reading data (e.g., fs.createReadStream() ).

2. Writable Streams: For writing data (e.g., fs.createWriteStream() ).

3. Duplex Streams: For both reading and writing (e.g., net.Socket ).

4. Transform Streams: A type of Duplex stream that can modify or transform


data as it is read or written (e.g., zlib.createGzip() for compressing data).

Example:

Node JS Interview Topics: 4


Buffer & File System:
Buffer:
Buffer is used to handle binary data directly in Node.js.

It is particularly useful when dealing with file streams, reading from or


writing to a file, working with TCP streams, or any other I/O operations

Node JS Interview Topics: 5


where raw binary data is involved.

Buffers allow you to interact with raw memory directly, which is not possible
with standard JavaScript data types like strings.

File System (fs) Module:


The File System (fs) module allows you to interact with the file system of
your computer.

It includes methods for reading, writing, updating, and deleting files,


creating directories, and more.

It supports both synchronous and asynchronous methods for file


operations.

Example:

Node JS Interview Topics: 6


Global Objects:
Global objects are objects that are available in all modules without needing to
import them. These objects are a part of the global scope and can be accessed
anywhere within a Node.js application. Unlike the browser's window object,
Node.js provides a global object, which contains various properties and
methods essential for Node.js applications.

Comman global objects:


1. : The global namespace object in Node.js, similar to
global window in the
browser.

2. __dirname : The directory name of the current module.

3. __filename : The full path of the current module file.

4. console : A global object used for logging output to the console.

5. : Provides information about and control over the current Node.js


process

process.

6. , setInterval , setImmediate : Timer functions for scheduling


setTimeout

asynchronous operations.

Example:

Node JS Interview Topics: 7


Modules:
Modules are reusable pieces of code that can be easily imported and exported
across different files in a Node.js application. They help in organizing code,
improving maintainability, and preventing code duplication. Node.js uses the
CommonJS module system, where each file is treated as a module.

Types of Modules:
1. Core Modules: Built into Node.js (e.g., fs , http , path ).

2. Local Modules: Custom modules created by users.

3. Third-party Modules: Modules installed via npm (e.g., express , lodash ).

Example:

1. Creating a Local Module

2. Using the Local Module

Node JS Interview Topics: 8


Explanation:

Local Module ( mathOperation.js )

Exports two functions: add and multiply .

Uses module.exports to make these functions available for import.

Main File ( app.js )

Uses require to import the mathOperations module.

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.

2. Router-level Middleware: Associated with an instance of express.Router() .

Node JS Interview Topics: 9


3. Built-in Middleware: Middleware that comes with Express, such as
express.json() .

4. Error-handling Middleware: Handles errors in the application.

5. Third-party Middleware: Middleware functions created by others and


available via npm (e.g., body-parser , cors ).

Example: Application-level Middleware in Express.js

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.

Key Concepts of Routing:

Node JS Interview Topics: 10


1. HTTP Methods: Different methods like GET , POST , PUT , and DELETE define
the type of operation the server should perform.

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

Node JS Interview Topics: 11


in a way that maintains a good user experience, logs relevant information for
debugging, and prevents crashes.

Methods for Error Handling


1. try / catch Blocks: Useful for handling errors in synchronous code or when
using async/await in asynchronous code.

2. Error-first Callbacks: A common pattern in Node.js where callbacks take


an error as their first argument (e.g., function(err, data) ).

3. Promise .catch() Method: Used for handling errors when working with
Promises.

4. Express Error Handling Middleware: Custom middleware functions for


handling errors in Express applications.

Example:

Node JS Interview Topics: 12


Request & Response:
Request and Response objects in Node.js are fundamental to handling HTTP
communication between clients and servers, especially when using a
framework like Express.js. When a client (like a browser or an API consumer)
makes a request to a server, the Request (req) object represents that incoming
request, containing details like HTTP method, URL, headers, and any data sent
with the request. The Response (res) object is used by the server to send back
data or responses to the client.

Key Properties and Methods:


req (Request Object):

req.method : The HTTP method used (e.g., GET , POST ).

req.url : The URL path of the request.

req.headers : An object containing request headers.

Node JS Interview Topics: 13


req.params : Contains route parameters (e.g., :id ).

req.query : Contains query string parameters.

req.body : Contains data sent in the body of the request (requires


middleware like express.json() ).

res (Response Object):

res.status() : Sets the HTTP status code of the response.

res.send() : Sends a response back to the client.

res.json() : Sends a JSON response.

res.redirect() : Redirects the client to a different URL.

Explanation:
Middleware:

Node JS Interview Topics: 14


app.use(express.json()) parses JSON data in the request body, allowing
access to req.body for POST requests.

GET Route:

Logs the request method ( GET ) and URL ( / ) using req.method and
req.url .

Uses res.send() to send a plain text response back to the client.

GET Route with Query Parameters:

Extracts the q parameter from req.query and includes it in the response.

Example: http://localhost:3000/search?q=nodejs will respond with "You


searched for: nodejs".

POST Route:

Extracts name and email from req.body and sends back a JSON
response using res.json() .

Uses res.status(201) to indicate that a new resource has been created.

Starting the Server:

Uses app.listen to start the server on port 3000.

Authentication and Authorization:


Authentication and Authorization are crucial concepts in any web application,
and they ensure that only legitimate users can access the resources they are
entitled to. In Node.js, these processes are often implemented using libraries
like Passport.js, JWT (JSON Web Tokens), and Express.

Authentication vs. Authorization:


Authentication:

This process verifies the identity of a user. It answers the question,


"Who are you?"

Common methods include username/password, tokens (like JWT),


OAuth, etc.

Successful authentication results in the server issuing a token (like a


JWT) that can be used to verify the user in subsequent requests.

Node JS Interview Topics: 15


Authorization:

This process determines what resources or actions a user is permitted


to access. It answers the question, "What can you do?"

Authorization typically happens after authentication.

For example, even after logging in, a user may only be allowed to view
their own profile and not that of another user.

Common Authentication Methods:


1. JWT (JSON Web Tokens): Tokens are issued to the client upon successful
login. These tokens can be sent with each request for authentication.

2. Session-Based Authentication: The server stores session data and sends


a session identifier to the client. This identifier is used to match the session
data stored on the server.

3. OAuth: Used for third-party authentication, often seen in "Login with


Google/Facebook" flows.

Example:

Node JS Interview Topics: 16


Restful API’s:
A RESTful API (Representational State Transfer API) is an architectural style for
designing networked applications. It allows for interaction with resources (such
as users, products, data) over the web using standard HTTP methods like GET,

Node JS Interview Topics: 17


POST, PUT, PATCH, and DELETE. A RESTful API provides a way for clients to
access and manipulate resources on a server in a stateless and standardized
manner.

Key Principles of RESTful APIs:


1. Stateless: Each request from the client to the server must contain all the
information the server needs to fulfill that request. The server does not
store the state of the client.

2. Uniform Interface: Uses standard HTTP methods and status codes for
consistency.

3. Resource-based: Each resource (like users, products, orders) is identified


by a URI (Uniform Resource Identifier), such as /users , /products/1 .

4. Representation of Resources: Resources can be represented in various


formats like JSON, XML, etc., with JSON being the most common.

5. Client-Server Architecture: The client and server are separate entities,


allowing for flexibility in development.

6. Cacheable: Responses can be cached to improve performance where


applicable.

HTTP Methods and Their Usage:


GET: Retrieve data from the server (e.g., GET /users ).

POST: Create a new resource on the server (e.g., POST /users ).

PUT: Update an existing resource entirely (e.g., PUT /users/1 ).

PATCH: Update a part of an existing resource (e.g., PATCH /users/1 ).

DELETE: Delete a resource (e.g., DELETE /users/1 ).

Example:

Node JS Interview Topics: 18


Node JS Interview Topics: 19
Explanation:
GET /users :

Responds with all users from the users array.

GET /users/:id :

Uses req.params to access the user ID from the route.

Searches for the user and returns a 404 status if not found.

POST /users :

Uses req.body to extract new user data.

Adds a new user to the users array and assigns a new ID.

Responds with a 201 status code to indicate successful creation.

PUT /users/:id :

Updates the entire user data for a given ID.

Replaces the existing user object with the new data.

DELETE /users/:id :

Finds and removes the user from the array.

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.

Key Aspects of API Security:


1. Authentication: Verifying the identity of users or applications accessing the
API (e.g., using JWT tokens, OAuth).

2. Authorization: Determining what resources or actions a user is permitted to


access after they have been authenticated.

Node JS Interview Topics: 20


3. Data Encryption: Encrypting data in transit (using HTTPS) and at rest to
protect it from interception and unauthorized access.

4. Rate Limiting: Preventing abuse of the API by limiting the number of


requests a client can make in a given time period.

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).

6. CORS (Cross-Origin Resource Sharing): Configuring CORS to restrict


which domains can access your API to prevent unauthorized requests from
other origins.

7. Error Handling: Properly handling errors to avoid leaking sensitive


information about the API’s internals.

Example: Using JWT, Rate Limiting, and Helmet

Node JS Interview Topics: 21


Node JS Interview Topics: 22
Explanation:
Helmet:

Sets various HTTP headers like X-Content-Type-Options , X-Frame-Options ,


and Strict-Transport-Security to make the app more secure.

Rate Limiting:

Limits each client to a maximum of 100 requests per 15 minutes to


prevent brute-force or DDoS (Distributed Denial of Service) attacks.

JWT Authentication:

Uses JWT for user authentication, allowing users to obtain a token upon
successful login.

The authenticateToken middleware verifies the token on protected routes


to ensure that only authenticated users can access those routes.

Best Practices for API Security:


1. Use HTTPS: Always encrypt data in transit using HTTPS to prevent data
interception.

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).

4. Implement Role-Based Access Control (RBAC): Restrict access to


resources based on user roles (e.g., admin, user).

5. Use Environment Variables: Store sensitive information like database


credentials, API keys, and secrets in environment variables.

6. Enable CORS Correctly: Configure CORS to restrict which domains can


access your API, preventing unauthorized cross-origin requests.

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

Node JS Interview Topics: 23


the application behaves correctly, and preventing security vulnerabilities like
SQL injection, XSS (Cross-Site Scripting), or even logical errors.

Common Ways to Validate Data in Node.js:


1. Using Validation Libraries: Libraries like Joi, Validator.js, or Yup make
validation straightforward and robust.

2. Custom Validation Logic: Writing custom validation functions or


middlewares when you have unique validation requirements.

3. Schema Validation in MongoDB: If using MongoDB, schema validation can


also be enforced at the database level using Mongoose.

Example:

Joi Validation

Joi.object() : Defines a schema object for validating user data.

Joi.string().min(3).max(30).required() : Ensures that the username is a string


between 3 and 30 characters and is required.

Joi.string().email().required() : Validates that the email field is a valid


email address.

Node JS Interview Topics: 24


Joi.string().min(8).required() : Validates that the password is a string with a
minimum length of 8 characters.

Handling Validation Errors:

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.

Example: Custom Validation

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:

Node JS Interview Topics: 25


Full-Duplex Communication: Both the client and server can send and
receive messages independently and simultaneously.

Reduced Latency: WebSockets maintain a persistent connection, reducing


the overhead of opening and closing multiple HTTP connections.

Lower Bandwidth Consumption: The protocol uses less overhead than


HTTP, making it more efficient for frequent communication.

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.

2. Authentication and Authorization: Implement strong authentication


mechanisms (e.g., token-based authentication) to ensure that only
authorized clients can connect to the WebSocket server.

3. Origin Checking: Validate the origin of WebSocket connections to prevent


cross-origin attacks.

4. Rate Limiting: Apply rate limiting to prevent abuse and denial-of-service


attacks.

5. Input Validation: Always validate and sanitize input data received through
WebSocket messages to prevent injection attacks.

6. Handling Disconnections: Properly handle unexpected disconnections and


reconnections to maintain application stability.

Example: WebSocket Server with Security

Node JS Interview Topics: 26


Example: Client Side

Node JS Interview Topics: 27


Event Emitter:
It is a core component of the Node.js Event module that allows objects to
communicate with one another by emitting and listening for events. This pattern
is particularly useful for creating asynchronous applications where different
parts of the application can react to various events, enabling a decoupled
architecture.

Features of Event Emitter:


1. Asynchronous Communication: Enables non-blocking, event-driven
programming, allowing different parts of the application to communicate
without being tightly coupled.

Node JS Interview Topics: 28


2. Multiple Listeners: Supports multiple listeners for the same event, enabling
various functionalities to be triggered by a single event emission.

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.

Listener: A function that is called when a specific event occurs.

Event: A named signal indicating that something has happened.

How It Works:
1. You create an instance of the EventEmitter class.

2. You define events and their corresponding listeners.

3. You emit events to trigger the associated listeners.

Example:

Node JS Interview Topics: 29


Clustering:
It is a technique that allows you to take advantage of multi-core systems by
spawning multiple instances of your Node.js application, each running on a
separate core. This approach can help improve the performance and scalability
of your application by distributing incoming connections and workloads across
several instances, effectively allowing Node.js to handle a higher volume of
requests.

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.

Node JS Interview Topics: 30


2. Fault Tolerance: If one worker crashes, the master process can spawn a
new worker to replace it, enhancing the resilience of the application.

3. Efficient Resource Utilization: Utilizes all available CPU cores, leading to


better performance on multi-core systems.

How Clustering Works:


1. A master process is created that controls the worker processes.

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:

Node JS Interview Topics: 31


The cluster.isMaster check determines if the current process is the
master. The master process forks worker processes based on the
number of CPU cores available.

Each worker is a separate instance of the application that can handle


requests independently.

The master process listens for exit events from workers and logs when
a worker dies.

Worker Processes:

In the else block, which is executed by worker processes, we create an


HTTP server.

Each worker listens for incoming requests on the same port (8000),
allowing them to share the same TCP connection.

The server responds with a simple "Hello, World!" message.

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 ).

2. File Caching: Stores data in temporary files on the filesystem.

3. Distributed Caching: Uses a separate caching layer (e.g., Redis,


Memcached) to store data across multiple servers.

Example:

Node JS Interview Topics: 32


Load balancing:
The technique of distributing incoming network traffic across multiple servers
or instances of an application to ensure that no single server becomes
overwhelmed. This helps enhance the availability and reliability of applications
while improving their performance by making efficient use of resources.

Types of Load Balancing:


1. Round Robin: Distributes requests sequentially to each server.

2. Least Connections: Sends requests to the server with the fewest active
connections.

3. IP Hash: Routes requests based on the client's IP address.

4. Weighted Load Balancing: Assigns different weights to servers based on


their capacity, directing more traffic to stronger servers.

Node JS Interview Topics: 33


Example:

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

Node JS Interview Topics: 34


variables). Understanding how these work is essential for effective memory
management.

Garbage Collection: Node.js employs a garbage collector to automatically


reclaim memory that is no longer in use. This helps in managing memory
more efficiently but requires developers to write code that minimizes the
likelihood of memory leaks.

Memory Leaks: A memory leak occurs when allocated memory is not


properly released, leading to increased memory usage over time. This can
cause the application to slow down or crash.

Memory Management Techniques:


1. Scope Management: Limit the scope of variables to minimize memory
usage. Use local variables instead of global ones whenever possible.

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:

Node JS Interview Topics: 35


Identifying Memory Leaks:
To identify and fix memory leaks, consider using the following approaches:

1. Node.js Debugger: Use the built-in debugger to step through your code
and analyze memory allocation.

2. Heap Snapshots: Take heap snapshots using Chrome DevTools to identify


objects that are not being released.

3. Monitoring Tools: Utilize monitoring tools like clinic.js or node-clinic to


visualize memory usage and detect leaks.

Best Practices:
1. Minimize Global Variables: Use local variables and encapsulation to limit
the scope of memory usage.

2. Use WeakMap and WeakSet : These allow objects to be garbage collected if


there are no strong references, helping to prevent memory leaks.

Node JS Interview Topics: 36


3. Explicitly Nullify References: After you’re done with an object, explicitly set
its reference to null to aid garbage collection.

4. Regular Profiling: Regularly profile your application to catch memory leaks


early during development.

Node JS Interview Topics: 37

You might also like