0% found this document useful (0 votes)
12 views36 pages

TCS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views36 pages

TCS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

TCS follows a five-pillar approach to diversity, equity, and inclusion (DEI): representation, culture,

enablement, engagement, and development.

 Diversity in the workplace refers to the inclusion and representation of individuals from a
variety of backgrounds, including differences in race, gender, age, ethnicity, sexual
orientation, disability, education, and other attributes.
 Enhanced Innovation and Creativity: Diverse teams bring different perspectives and ideas,
leading to innovative solutions and creative thinking.
 Better Decision Making: Varied viewpoints improve problem-solving and decision-making
processes.
Equality:

 Definition: Equality means treating everyone the same and giving everyone the same
opportunities, resources, and treatment.

Equity:

 Definition: Equity means recognizing that different individuals have different needs and
circumstances, and providing varying levels of support and resources to ensure fair
outcomes.

Inclusion in the workplace refers to creating an environment where all employees feel valued,
respected, and able to contribute fully, regardless of their diverse backgrounds and characteristics.

Recognizing and appreciating the unique perspectives, experiences, and skills that each employee
brings to the organization.

NodeJS

https://www.geeksforgeeks.org/node-interview-questions-and-answers/

MongoDB

https://www.youtube.com/watch?v=9xB0aojRQ_U
HR Questions
AWS

GOOGLE CLOUS

MICROSOFT AZURE
IF YOU ARE SICK, HOW WILL YOU TACKLE YOUR PRESENTATION. - "Presentations are a critical part of
our work, and I take them very seriously. To ensure I'm always ready, I prepare thoroughly in
advance, making sure all my materials are organized and accessible. If I happen to be sick on the day
of the presentation, I would leverage remote presentation tools like Zoom to present from home.
Additionally, I believe in having a backup plan, so I usually brief a colleague on my presentation
content who can step in if needed. Clear communication with my team is essential, so I would notify
them of my situation as soon as possible. While prioritizing my health, I would still do my best to
deliver the presentation effectively, ensuring that my temporary condition doesn't affect the team's
progress."

YOU ARE A TEAM LEADER. CLIENT IS CONTINUOSLY CHANGING THE REQUIREMENTS. HOW WILL YOU
DEAL WITH THE SITUATION. -

1. Open Communication

2. Clarify requirements

3. weekly check-ins to discuss progress and new requirements

4. keep proper updated documentation of the changes requested by the client

WHY DO YOU WANT TO JOIN TCS

*ANY TWO BOOKS YOU READ. GIVE SUMMARY IN ONE MINUTE.


3. Tell me 5 personal traits that you have.What ethics and values does TCS follow?

6. What is the difference between equity and equality?

7. What is most important to you?

 What are the four main principles of Object-Oriented Programming, and can you explain
each one briefly?

 What is an abstract class, and how does it differ from an interface in OOP?

An abstract class in C++ is a class that cannot be instantiated and is intended to be a base
class for other classes, containing at least one pure virtual function (i.e., a function declared
with = 0), which must be implemented by derived classes.

In Object-Oriented Programming (OOP), an interface is a blueprint that defines a set of


abstract methods that a class must implement, specifying what methods a class should have
without providing their implementation.

An abstract class in OOP can contain both abstract methods and implemented methods with
state (member variables), while an interface can only contain abstract methods with no
implementation or state.

 How does the virtual keyword work in C++, and what is its purpose in polymorphism?

In C++, the virtual keyword is used to indicate that a function is virtual, meaning it can be
overridden in any derived class. It is primarily used to enable polymorphism.

 When a base class function is declared as virtual, it allows derived classes to override that
function.

 This enables the program to call the correct function implementation depending on the
type of the object being referred to, even when using a base class pointer or reference.

 How do you manage dynamic memory in C++, and what are the common pitfalls to avoid?

Certainly! When managing dynamic memory in C++, use new for allocation and delete for
deallocation, and ensure to handle exceptions, avoid dangling pointers, and consider using
smart pointers (std::unique_ptr, std::shared_ptr) to automate memory management and
prevent leaks.

Common pitfalls include forgetting to free allocated memory (`delete`), causing memory
leaks, or accessing deleted memory leading to undefined behavior.

 What is a constructor in C++, and how does it differ from a destructor?

 Explain the concept of operator overloading in C++ with an example.

Operator overloading in C++ enables defining custom behaviors for operators (such as
arithmetic, comparison, or input/output operators) for user-defined classes, enhancing code
readability and abstraction by allowing intuitive syntax for complex operations and type
interactions.
 How does state management work in React, and what are some popular state management
libraries you can use with React?

 createContext function from the 'react' library. This context object will hold the data
that you want to share across your application.
 Once you've created a context object, you need to wrap the components that need
access to the shared data with a Provider component. The Provider component
accepts a "value" prop that holds the shared data, and any component that is a child
of the Provider component can access that shared data.
 we need to consume the context in other components. To do this, we use the
"useContext" hook from React.

 What is JSX, and how does it relate to React components?

 How can you optimize the performance of a React application?

 How do you create a table in HTML, and what are the main elements used in a table?

 Explain the difference between block-level and inline elements in HTML.

 What is the difference between var, let, and const in JavaScript?

In JavaScript, var is global-scoped and allows re-declaration, let is block-scoped and does not
allow re-declaration within the same scope, and const is also block-scoped but creates a
read-only reference, meaning the variable cannot be reassigned.

 How do you handle asynchronous operations in JavaScript?

Asynchronous operations in JavaScript are handled using callbacks, Promises, and the
async/await syntax, which allows writing asynchronous code that appears synchronous,
improving readability and manageability of complex asynchronous workflows.

 What is the Document Object Model (DOM)?

 Explain the concept of closures in JavaScript with an example.

Closure in JavaScript is a form of lexical scoping used to preserve variables from the outer
scope of a function in the inner scope of a function. Lexical scoping is the process used to
define the scope of a variable by its position in the source code.function createCounter() {

let count = 0; // This variable is in the lexical scope of the inner function

return function() {

count++; // The inner function has access to the `count` variable

return count;

};

const counter = createCounter(); // `createCounter` returns a function


console.log(counter()); // Output: 1

console.log(counter()); // Output: 2

console.log(counter()); // Output: 3

 What is the difference between == and === operators in JavaScript?

 What are the differences between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN
in MySQL?

 What is normalization, and why is it important in database design?

 And some questions on my project.

 About my group project.

Tell me something about yourself.

Are you ready to relocate and work in night shift if necessary for some projects.

What are your plans about future studies.

If you have 2 offers one from TCS and one from Infosys which one will you choose and why?

 TCS: Offers a wide range of projects across various industries, providing opportunities for
diverse experience. TCS also has a strong emphasis on continuous learning through its
platforms like TCS iON and TCS Elevate.
 TCS: Has a reputation for a stable work environment with a focus on long-term career growth
 Company Reputation: Both companies are highly reputable, but TCS is known for its stability
and market presence, while Infosys is recognized for its innovation and employee-friendly
policies.
 The company emphasizes work-life balance and employee welfare programs.

What is your opining on switching for salary hikes?

Form Validation Code Snippet:

They also asked logical question like why Bubble sort is named as “Bubble Sorting”.

If you get a chance to switch to other company will you be leaving from TCS.

WHAT IS UR FAVOURITE SUBJECT AND WHY?


STRENGTH AND WEAKNESS

HIGHER STUDIES
"Firstly, I would take a moment to understand the situation and ensure that I have all the facts. It’s
important to remain calm and not react impulsively."
I would reflect on the situation to consider if there might be reasons I’m not aware of for the credit
being given to someone else.

"I would schedule a private meeting with my manager to discuss the matter. I would express my
feelings professionally and provide specific examples of my contributions to the project."

"I would remain professional and continue to deliver my best work.


1. Explain the MERN tech stack.

2. If Node.js already exists, why do we need Express.js?

Express.js is needed because it simplifies building web applications and APIs in Node.js by
providing a robust set of features and a flexible, minimalist framework for handling routing,
middleware, and HTTP requests/responses.

3. Can I run two Node.js projects on my local machine, each requiring different versions of
Node.js?

Yes, you can run two Node.js projects on your local machine, each requiring different
versions of Node.js, by using a version manager like nvm (Node Version Manager) to switch
between Node.js versions as needed.

4. What is the purpose of the .env file?

The purpose of the .env file is to store environment variables. such as API keys, database
connections, and other sensitive information without hardcoding them in the source code.

API keys, passwords, and database credentials are kept out of the source code, reducing the
risk of accidental exposure.

5. How are applications rendered? If I want to run my application on another machine, what is
the process?

Applications are rendered by executing the server-side code (in the case of backend
applications) or by serving the static files (HTML, CSS, JavaScript) to the client (in the case of
frontend applications). Here’s the process to run your application on another machine:

 Install Dependencies:
Run npm install (or yarn install) in the application's directory to install all necessary
dependencies specified in package.json.

 Set Up Environment Variables:

 Start the Application:

 Use the appropriate start command, typically npm start for backend applications, to start the
server.

6. What are RESTful APIs? Can the work of a POST request be done using a PUT request?

7. What is the difference between an exception and an error?

Error:

 What it is: A serious problem that typically indicates something went very wrong with the
system or the environment where the program is running.

 Recoverability: Usually not recoverable. When an error occurs, the program often cannot
continue running.

 Examples: Running out of memory, hardware failures, or JVM crashes.

 Handling: Not meant to be caught or handled by the program.

Exception:

 What it is: A problem that occurs during the execution of a program, usually related to the
program logic or external conditions.

 Recoverability: Often recoverable. The program can catch and handle exceptions to allow it
to continue running or to perform specific corrective actions.

 Examples: File not found, invalid user input, network connection issues.

 Handling: Meant to be caught and handled by the program using try-catch blocks.

8. Can I use MongoDB from the command line interface (CLI)?

Yes, you can use MongoDB from the command line interface (CLI). MongoDB provides a CLI
tool called mongo for interacting with MongoDB databases.

$ mongod

# Starts the MongoDB server

$ mongo

# Opens the MongoDB shell

> use myDatabase


# Switches to 'myDatabase'

> db.myCollection.insertOne({ name: "Jane Doe", age: 25 })

# Inserts a document into 'myCollection'

> db.myCollection.find()

# Queries all documents in 'myCollection'

> db.myCollection.updateOne({ name: "Jane Doe" }, { $set: { age: 26 } })

# Updates the document where name is "Jane Doe"

> db.myCollection.deleteOne({ name: "Jane Doe" })

# Deletes the document where name is "Jane Doe"

9. Is MongoDB NoSQL or SQL?

10. What is state management in React?

State management in React refers to the practice of handling and synchronizing the state
(data) of components within a React application to ensure that the UI accurately reflects the
current state of the application.

11. Can you explain APIs?

An API (Application Programming Interface) is a set of rules and protocols that allows
different software applications to communicate and interact with each other.

It enables to share data and functionalities.

 Request: A client application sends a request to the API endpoint (a specific URL) over
the internet or a network. This request includes an HTTP method (such as GET, POST, PUT,
DELETE), headers, and optionally a payload containing data.

 Processing: The API server receives the request, processes it, and performs the necessary
operations such as accessing a database, executing business logic, or interacting with other
services.

 Response: The API server sends a response back to the client. This response typically
includes a status code (indicating success or failure), headers, and a payload containing the
requested data or the result of the operation.

12. What is the difference between GET and POST requests?


13. Can a PUT request be used to perform the work of a POST request?

14. Design a database for your college. Can teachers and students be in the same table as users?

15. What subject are you most confident in?

 I answered DSA (Data Structures and Algorithms), so he asked further questions:

o What motivates you to study DSA?

o What algorithms have you learned in DSA?

o He specifically asked about Dijkstra’s Algorithm and where it is used, as well


as any mobile applications where it might be applied.

Algorithms – Sorting, Searching, graph, DP Algorithms

Managerial Round:

Here are the questions related to the managerial round:

1. Explain the software life cycle.

Summary of SDLC Phases:

1. Planning: Define project scope and feasibility.

2. Requirements Analysis: Gather and document user requirements.

3. Design: Architect the software system.

4. Implementation: Write and test code.

5. Testing: Validate the software against requirements.

6. Deployment: Release the software to users.

7. Maintenance: Provide ongoing support and updates.

2. If there are dynamic conditions requiring you to work in shifts, including day and night, are
you comfortable with that?

3. He also asked some family-related questions:

 Do you have siblings? What are they doing, and what are their future plans?

HR Round:

1. Where is your hometown?

2. Are you aware of TCS Prime and TCS Digital?

3. Would you strictly prefer TCS Prime, or would you accept TCS Digital if offered?

4. Are you comfortable with relocating a long distance, such as from Lucknow to Chennai?
What is ‘agile’ software development?

Agile Software Development is a software development methodology that values flexibility,


collaboration, and customer satisfaction. It is based on the Agile Manifesto, a set of principles for
software development that prioritize individuals and interactions, working software, customer
collaboration, and responding to change.

 What is the difference between Verification and Validation?

In authentication, verification ensures that the provided credentials (like a password) are
correct and match the stored credentials, while validation confirms that the authenticated
user has the appropriate permissions to access a specific system or resource.

 What is a token? What is the difference between token-based and cookie-based


authentication? How can we implement them?

A token is a piece of data used to authenticate and authorize users in a system. Token-based
authentication stores tokens on the client-side and sends them with each request, while
cookie-based authentication stores session information on the server and uses cookies to
maintain the session.

Token-Based Authentication:

 User Login:

 The user sends a login request with their credentials (username and password) to the server.

 Token Generation:

 The server verifies the credentials.

 If valid, the server generates a token (often a JWT - JSON Web Token) and sends it back to
the client.

 Storing Token:

 The client stores the token, typically in local storage or session storage.

 Using the Token:

 For subsequent requests, the client includes the token in the Authorization header (e.g.,
Authorization: Bearer <token>).

 Token Verification:

 The server verifies the token on each request.

 If the token is valid, the server processes the request and returns the appropriate response.

 Token Expiration and Refresh:

 Tokens typically have an expiration time. The client might request a new token using a
refresh token when the token expires.

Cookie-Based Authentication:

1. User Login:
o The user sends a login request with their credentials (username and password) to
the server.

2. Session Creation:

o The server verifies the credentials.

o If valid, the server creates a session and stores session information server-side.

o The server sends a session ID back to the client in a cookie.

3. Storing Cookie:

o The browser automatically stores the cookie.

4. Using the Cookie:

o For subsequent requests, the browser automatically includes the cookie in the
request headers.

5. Session Verification:

o The server retrieves session information using the session ID from the cookie.

o If the session is valid, the server processes the request and returns the appropriate
response.

6. Session Expiration:

o Sessions can have an expiration time or be invalidated by the server

API Integration: Discuss your experience with API integration by providing a code snippet or
explaining the process of fetching data from an API. Highlight your ability to work with external
systems and services.

Form Validation Code Snippet: Present a code snippet demonstrating form validation, ensuring that
inputs meet specific criteria such as allowing only characters in a name field. Showcase your
knowledge of client-side validation techniques.

JWT CODE

Pointers and their uses

Uses of Pointers:

1. Dynamic Memory Allocation:

2. Function Arguments (Passing by Reference):

3. Data Structures (Linked Lists, Trees, Graphs):


explain inheritance & write code

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class


(called the derived or child class) to inherit properties and behaviors (methods) from another class
(called the base or parent class). This promotes code reuse, modularity, and the creation of a
hierarchical relationship between classes.

Types of Inheritance:

1. Single Inheritance:

o A derived class inherits from a single base class.

Multiple Inheritance:

 A derived class inherits from more than one base class.

Multilevel Inheritance:

 A derived class inherits from another derived class.

Hierarchical Inheritance:

 Multiple derived classes inherit from a single base class.

Hybrid Inheritance:

 A combination of two or more types of inheritance.

FUNCTION OVERRIDING CODE

https://www.geeksforgeeks.org/function-overriding-in-cpp/

A **library** is a collection of reusable code that developers call to perform specific tasks, whereas a
**framework** provides a structured environment with predefined flow and rules, where
developers fill in the code to build an application.

Explain the difference between a class component and a functional component.

A class component in React.js is defined using ES6 classes, manages its own state, and utilizes
lifecycle methods for handling component updates and interactions.

A functional component in React.js is a simpler, stateless component defined as a JavaScript function


that takes props as an argument and returns JSX.

WHAT ARE PROPS?

Props (short for properties) in React are used for passing data from one component to another,
enabling communication between components in a unidirectional flow.
WHAT IS THE SIGNIFICANCE OF KEYS IN REACT?

 Help React identify and track elements during updates.

 Improve performance by minimizing re-renders.

 Keys should be unique among siblings.

This ensures proper state management and avoids unnecessary re-rendering of components,
optimizing performance.

WHAT ARE REACT HOOKS?

React Hooks are functions that allow functional components in React to use state, lifecycle methods,
and other React features without needing to write a class component. They were introduced in React
16.8 as a way to enable stateful logic in functional components

USEEEFECT HOOKS:

 Fetching Data: Use useEffect to fetch data from an API or perform asynchronous tasks when the
component mounts.

 Updating the DOM: Use useEffect to update the DOM or perform imperative operations after a
component renders.

 Subscribing to Events: Use useEffect to subscribe to events or integrate with third-party libraries
that need cleanup.

 Managing Side Effects: Use useEffect to manage any side effects that should occur in response to
props or state changes.

Cleanup: It facilitates cleanup operations when the component unmounts or when dependencies
change.

WHAT ARE HIGHER ORDER COMPONENTS?

Higher-order components (HOCs) in React are functions that take a component as an argument and
return a new enhanced component, allowing you to reuse component logic, share code between
components, and add additional features such as state management, context access, or props
manipulation without modifying the original component's structure.

What are controlled and uncontrolled components in React?

In React, Controlled components refer to the components where the state and behaviors are
controlled by Parent components.

uncontrolled components manage their own state internally using refs or rely on DOM directly.

CONTEXT API CODE


STATE LIFTING IN REACT

“Lifting State Up” is a concept in React that involves moving the state of a component higher up in
the component tree. In React, the state is typically managed within individual components, but there
are situations where multiple components need to share and synchronize the same state. When this
happens, you can lift the state to a common ancestor component that is higher in the component
hierarchy.

Pass State Down as Props: Once the state is moved to the common ancestor, pass it down to the
components that need access to it as props.

ERROR BOUNDARIES IN REACT

Error boundaries in React are components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of crashing the entire application.
They help to isolate errors and prevent them from affecting the entire application UI.

Explain code-splitting and lazy loading in React.

Code-Splitting:

 Definition: Code-splitting involves breaking down your JavaScript bundle into smaller chunks
(or bundles) based on different parts of your application.

 Purpose: It helps reduce the initial bundle size sent to the client, speeding up the initial load
time of your application.

 Implementation: React provides a built-in React.lazy function and Suspense component for
declarative code-splitting.

Lazy Loading:

 Definition: Lazy loading refers to loading resources (like components, modules, or data) only
when they are needed, rather than loading everything upfront.

 Purpose: It optimizes performance by reducing the amount of initial data that needs to be
loaded, especially useful for large applications or complex UIs.

How do you optimize React performance?

 Use Functional Components with Hooks: Prefer functional components over class components
and utilize React Hooks (useState, useEffect, etc.) to manage state and lifecycle events more
efficiently.

 Memoization with React.memo: Use React.memo to memoize functional components and


prevent unnecessary re-renders when props or state do not change.

Implement code-spiliting and Lazy loading.


`useMemo` is a React hook that memoizes the result of a function and re-computes it only when
its dependencies change, optimizing performance by caching expensive computations.

useCallback memoizes functions to optimize performance by returning a stable reference to a


function instance.

REDUX

 Store: Holds the application state and provides methods to access and update it.

 Actions: It is a payload of information that transmits data from an application to a store. They are
the sole source of information for the store. One can send them to the store using store. dispatch()

 Reducers: Functions that specify how the application's state changes in response to actions,
ensuring that state transitions are predictable.

 Selectors: Functions used to extract specific pieces of state from the store, encapsulating the state
shape details and promoting reusability.

CUSTOM HOOKS

Custom hooks are JavaScript functions that utilize existing hooks (like useState, useEffect,
useContext, etc.) to encapsulate logic and state management for reuse across different components.
They enable developers to extract component logic into reusable functions, promoting code reuse
and separation of concerns.

REACT LIFECYCLE METHOD

11. What do you mean by event loop in Node.js?

The event loop in Node.js is a mechanism that allows it to handle multiple asynchronous tasks
concurrently within a single thread. It continuously listens for events and executes associated
callback functions.

What are global objects in Node.js? Give examples.

Global objects in Node.js are objects that are available globally across all modules in a Node.js
application without needing to import them explicitly. Some examples of global objects in Node.js
include:

 console: Used to print to stdout and stderr.

 setTimeout, setInterval: Functions for executing code asynchronously after a delay or at intervals.

 __dirname: The name of the directory that currently contains the script being executed.

 __filename: The filename of the script being executed.

 require: Function to import modules.


 module, exports, global: Global variables related to modules and global context.

What is middleware?

Middleware is the function that works between the request and the response cycle. Middleware gets
executed after the server receives the request and before the controller sends the response.

Here’s how middleware works in an Express.js application:

1. Middleware Function: A middleware function in Express.js is typically written with three


parameters: req (request object), res (response object), and next (a function to call the next
middleware function in the stack).

Mounting Middleware: Middleware functions are mounted using app.use() or specific HTTP method
functions (app.get(), app.post(), etc.) in Express.js.

Order of Execution: Middleware functions are executed sequentially in the order they are mounted.
They can modify req and res objects and can also end the request-response cycle by sending a
response directly (res.send(), res.json(), etc.) without calling next(), which passes control to the next
middleware function.

How can you read and write files in Node.js?

In Node.js, file operations are facilitated by the built-in fs (File System) module, which provides a
wide range of methods for interacting with the file system.

Asynchronous Read Operations: fs.readFile(path[, options], callback)

Synchronous Read Operations: fs.readFileSync(path[, options])

SAME FOR FS.WRITEFILE()

What are streams in Node.js? Explain different types of streams.

In Node.js, streams are objects that enable you to read data from a source or write data to a
destination in a continuous fashion. Streams are especially useful for handling large amounts of data
efficiently, without loading it all into memory at once.

Readable Streams:

 Readable streams allow Node.js to read data from a source in a sequential manner.

Writable Streams:

 Writable streams allow Node.js to write data to a destination in a sequential manner.

Duplex Streams:

 Duplex streams represent streams that are both readable and writable.

Transform Streams:
 Transform streams are a special type of duplex stream where the output is computed based
on the input.

Explain the difference between blocking and non-blocking code.

Blocking code halts further execution until an operation completes, while non-blocking code allows
the program to continue executing other tasks concurrently.

Effect: If one part of the code is blocking, the entire program waits until that operation completes,
potentially causing delays and reducing overall concurrency.

Effect: Improves efficiency and responsiveness as the program can handle multiple operations
concurrently, often using callbacks, promises, or async/await syntax in languages like JavaScript or
using event-driven models like in Node.js.

EXAMPLE : SYNCHRONOUS AND ASYNCHRONOUS FUNCTIONS

How can you handle asynchronous operations in Node.js?

 Callback Functions: Callback functions are functions passed as arguments to other functions,
typically invoked once an asynchronous operation completes, allowing for continuation of program
execution.

 Promises: Promises are objects representing the eventual completion or failure of an


asynchronous operation, providing a cleaner syntax for chaining asynchronous tasks and handling
errors.

 Async/Await: Async/Await is a syntactic sugar built on top of promises, simplifying asynchronous


code by allowing you to write asynchronous functions that look synchronous, enhancing readability
and maintainability.

What are some common built-in modules in Node.js?

 fs: Provides an API for interacting with the file system, allowing you to read, write, and manipulate
files and directories.

 http: Enables building HTTP servers and making HTTP requests, with methods for handling
incoming HTTP requests and sending responses.

 path: Offers utilities for working with file and directory paths, such as resolving paths, joining
paths, and extracting file extensions.

os: , allowing you to retrieve information about the operating system, CPU architecture, memory,
and network interfaces.

What is clustering in Node.js and how does it improve performance?


clustering in Node.js optimizes performance by distributing workload across multiple CPU cores,
enabling applications to handle more concurrent requests efficiently and reliably.

Describe how you can secure a Node.js application.

 Secure Authentication and Authorization: Use secure authentication mechanisms like JWT, OAuth,
or session-based authentication with secure session storage and implement role-based access
control (RBAC).

Implement HTTPS: Use HTTPS for secure communication between clients and servers to encrypt
data and prevent man-in-the-middle attacks.

Enable CORS: Configure Cross-Origin Resource Sharing (CORS) headers properly to restrict which
domains can access your APIs.

How would you optimize a Node.js application for performance?

1. Using asynchronous operations

2. implementing clustering

3. Use Streaming

4. Use efficient data transfer formats (e.g., JSON instead of XML) and minimize the number of HTTP
requests between frontend and backend.

const http = require('http');

// Create a server object

http.createServer(function (req, res) {

res.write('Hello World!');

res.end();

}).listen(3000);

 setTimeout() method

 setImmediate() method

 setInterval() method

What is a NoSQL database? How does it differ from a SQL database?


In NoSQL database we store data in different form other than tabular relations like in relational
databases.

Explain the difference between a database, a collection, and a document in MongoDB.

 Database:

 Definition: A database in MongoDB is a container that holds collections of documents.

 Usage: It is used to group collections that are logically related to each other. Each database
has its own set of permissions and authentication controls.

 Collection:

 Definition: A collection in MongoDB is a group of MongoDB documents. It is analogous to a


table in relational databases but does not enforce a schema.

 Usage: Collections hold individual JSON-like documents, which can vary in structure.
Documents within a collection are typically related to each other based on the application's
data model.

 Document:

 Definition: A document in MongoDB is a set of key-value pairs (fields) and is the basic unit of
data in MongoDB. It resembles JSON objects and is stored in BSON (Binary JSON) format.

 Usage: Documents represent entities or records within a collection and can contain nested
documents, arrays, and other complex data types.

How do you start the MongoDB server and connect to it using the Mongo shell?

Mongod

 This command starts the MongoDB server process. By default, it listens for connections on port
27017.

 MongoDB will start and begin accepting connections.

Mongo

This command starts the MongoDB shell and connects to the MongoDB server running on the
default port (27017) on localhost.

Create a database - use mydatabase

Create a collection - db.createCollection("users")

WHAT ARE INDEXES IN MONGODB?


Indexes in MongoDB are additional data structures that store a sorted or hashed subset of the data,
allowing for efficient query execution by quickly locating documents based on the indexed fields,
thereby reducing the need to scan the entire collection. They are crucial for optimizing query
performance, enabling faster read operations, and supporting efficient data retrieval in large-scale
applications.

How do you create and use indexes in MongoDB?

db.collection.createIndex({ field: 1 });

db.collection.createIndex({ content: "text" }); FOR TEXT INDEX

What is aggregation in MongoDB?

Aggregation in mongodb involves performing set of operations and process data within a collection,
allowing tasks such as grouping documents, calculating aggregate values and performing
transformations like sorting. It makes mongodb highly flexible for data analysis.

Explain the different stages in an aggregation pipeline.

$match:

 Filters documents based on specified criteria.

$sort:

 Sorts documents based on specified fields.

$skip:

 Skips a specified number of documents in the input.

$limit:

 Limits the number of documents passed to the next stage.

How do you perform a text search in MongoDB?

db.collection.find({ $text: { $search: "searchTerm" } });

Describe the concept of sharding and its benefits.

Sharding in MongoDB enables the distribution of data across multiple servers (shards) to
accommodate large datasets, improve query performance, and ensure high availability by balancing
data and query loads effectively across the cluster. In this approach, data is divided into distinct
subsets known as shards, and MongoDB's query router directs queries to the relevant shard as
needed.
Explain replication and the role of replica sets.

 Replication in MongoDB is the process of synchronizing data across multiple servers called replicas.

 It ensures that if one server fails, data remains accessible from other replicas, preventing data loss
and downtime.

Role of Replica Sets:

 Replica sets in MongoDB are a group of MongoDB servers that maintain copies of the same
data.

 They consist of primary and secondary nodes where the primary handles all write operations
and replicates data to secondary nodes.

 If the primary node fails, one of the secondary nodes automatically becomes the primary to
ensure continuous availability and data integrity.

MongoDB supports various data types including strings, numbers, arrays, objects, dates, boolean
values

How do you monitor and optimize the performance of a MongoDB database?

1. Indexing

2. Sharding

3. schema design

22. How do you backup a MongoDB database?

You can back up a MongoDB database using tools like `mongodump` or by configuring regular
snapshots at the file system or cluster level.

What are the different types of indexes in MongoDB?

MongoDB supports various indexes, including single-field indexes, compound indexes, geospatial
indexes, text indexes, hashed indexes, and wildcard indexes.

GridFS represents a MongoDB standard designed to handle storing and retrieving substantial files,
such as images, videos, and binary data.

const mongoose = require('mongoose');

const Schema = mongoose.Schema;


const userSchema = new Schema({

username: {

type: String,

required: true,

unique: true,

},

email: {

type: String,

required: true,

unique: true,

},

password: {

type: String,

required: true,

},

createdAt: {

type: Date,

default: Date.now,

},

});

const User = mongoose.model('User', userSchema);

module.exports = User;

How do you handle errors in Express.js?


Middleware for Errors: Use middleware functions with four arguments (err, req, res, next) to catch
and handle errors in Express.

Async Error Handling: Use try-catch blocks or async/await with next(err) to handle asynchronous
errors effectively.

How do you serve static files in Express.js?

app.use(express.static('public'));

What is the purpose of next() in middleware?

1. it is used to pass the control to next middleware function in stack.

2. It is used for middleware chaining

3. It is used for error handling

What is routing and how do you define nested routes in Express.js?

Routing in Express.js refers to the mechanism of defining how an application responds to client
requests to specific endpoints (URL paths) and HTTP methods (GET, POST, PUT, DELETE, etc.). It
involves mapping HTTP requests to corresponding handler functions that process those requests and
generate responses.

Defining Nested Routes in Express.js

Nested routes in Express.js involve organizing routes hierarchically based on URL paths. This allows
you to structure your application's API or web routes in a more modular and logical manner.

app.get('/books', function(req, res) { res.send('GET all books'); }); // Nested routes under '/books'
app.get('/books/:id', function(req, res) { res.send(`GET book with ID ${req.params.id}`); });

How do you parse incoming request bodies in Express.js?

 Use express.json() for JSON bodies.

 Use express.urlencoded({ extended: true }) for URL-encoded bodies.

 Middleware processes incoming data into req.body.

Use middleware in routes: app.post('/upload', upload.single('file'), handler).

What is CORS and how do you handle it in Express.js?


CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers that
restricts web pages from making requests to a different domain than the one that served the original
web page.

How do you secure an Express.js application?

1. Using HTTPS to encrypt data during transmit. It ensures secure communication between client and
server.

2. Implementing Authentication and Authorization

3. Enabling CORS to restrict access to our APIs.

Write a middleware function in Express.js that logs the details of every request.

app.use((req, res, next) => {

console.log(`${req.method} ${req.url}`);

next();

});

What are the main components of an API?

 Answer: The main components of an API include:

o Endpoints: Specific paths where API services are made available.

o Methods: HTTP methods such as GET, POST, PUT, DELETE, etc.

o Headers: Metadata passed along with API requests and responses.

o Request Body: Data sent with the request, typically in POST or PUT methods.

o Response Body: Data returned by the API, usually in a format like JSON or XML.

o Authentication: Mechanisms to ensure that API calls are made by authorized users
(e.g., API keys, OAuth).

What are the main principles of RESTful architecture?

 Answer: The main principles of RESTful architecture include:

o Statelessness: Each request from the client to the server must contain all the
information needed to understand and process the request. The server does not
store client context.

o Client-Server Separation: The client and server are independent of each other; the
client does not need to know the server's implementation details and vice versa.

o Uniform Interface: The interface between client and server must be uniform,
typically defined by standard HTTP methods.
What is an endpoint in an API?

 Answer: An endpoint is a specific URL path on a server where an API service is made
available. It represents a resource and the operations that can be performed on it. For
example, in a RESTful API, an endpoint might look like https://api.example.com/users for
accessing user data.

1. 200 (Success/OK)

201 Created

400 (Bad Request)

401 (Unauthorized Error)

403 (Forbidden)

404 (Not Found)

500 (Internal Server Error)

What is the difference between synchronous and asynchronous API calls?

 Answer: In synchronous API calls, the client sends a request to the server and waits for a
response before continuing. This can lead to blocking behavior. In asynchronous API calls,
the client sends a request and can continue processing other tasks while waiting for the
server's response, which typically comes in the form of a callback or a promise.

What are the security concerns associated with using JWT and how can they be mitigated?

Concerns include token theft, token forgery, and data exposure. Mitigate these by using HTTPS to
encrypt data in transit, setting short token expiration times, securely storing tokens, and using
strong, secret keys.

How do you handle token expiration and renewal in a JWT-based system?

Use refresh tokens to issue new access tokens without requiring the user to log in again. Store
refresh tokens securely and use them to request new access tokens when the current ones expire.

WHAT IS STATIC DATA MEMBER ?


Static data members are class members that are declared using static keywords. A static member has
certain special characteristics which are as follows: Only one copy of that member is created for the
entire class and is shared by all the objects of that class, no matter how many objects are created.

What is a static member function in C++ with an example?

The static member functions are special functions used to access the static data members or other
static member functions. A member function is defined using the static keyword. A static member
function shares the single copy of the member function to any number of the class' objects.

It can be called without creating objects.

You might also like