BACKEND INTERVIEW QUESTIONS
1. What is [Link]? What are its main features?
[Link] is an open-source, cross-platform runtime environment that executes JavaScript code
outside of a browser. Its features include:
a. Non-blocking, event-driven architecture
b. Built on Chrome's V8 JavaScript engine
c. Single-threaded but highly scalable
2. How does the event loop work in [Link]?
The event loop in [Link] is responsible for handling asynchronous operations. It continuously
checks the call stack, handles events and callbacks, and ensures that asynchronous functions
are executed when their task is complete
3. What is the difference between synchronous and asynchronous code in
[Link]?
a. Synchronous code blocks the execution until the task is complete.
b. Asynchronous code doesn't block; it allows other code to execute while waiting
for a task to finish.
4. What are Promises in [Link]?
Promises represent the eventual completion or failure of an asynchronous operation.
let promise = new Promise((resolve, reject) => {
// asynchronous task
});
5. What is async/await, and how does it improve asynchronous code?
async/await simplifies working with Promises by allowing asynchronous code to be written
in a synchronous-looking manner. Example:
async function fetchData() {
const data = await fetch('url'); [Link](data);
}
6. What is the fs module in [Link]? How do you use it to perform file
operations? The fs module provides functions to interact with the file system.
Example for reading a
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err; [Link](data);
});
7. What are Streams in [Link]? What are the types of streams?
Streams in [Link] handle reading and writing data in chunks, rather than all at once.
Types of streams include:
a. Readable
b. Writable
c. Duplex (both readable and writable)
d. Transform (modify data while reading or writing)
8. Explain the use of the http module in [Link].
The http module allows the creation of HTTP servers and clients. Example:
const http = require('http');
[Link]((req, res) => {
[Link](200, {'Content-Type': 'text/plain'});
[Link]('Hello, world!');
}).listen(3000);
9. What is NPM, and how do you use it in [Link]?
NPM is the Node Package Manager, used to install, update, and manage packages in
[Link] applications. Example: npm install express
10. What is the purpose of the [Link] file in [Link]? [Link] is a
manifest file that defines the metadata for a [Link] project, including the project's
dependencies, scripts, version, and more.
11. What is clustering in [Link], and how does it improve performance?
Clustering allows a [Link] application to scale across multiple CPU cores by
creating worker processes. This helps in handling more requests by distributing them
across the cluster.
12. How do you handle exceptions in [Link]?
a. Use try/catch blocks for synchronous code.
b. For asynchronous code, use .catch() with Promises or handle errors in callback
functions. You can also listen for global events like
[Link]('uncaughtException') to handle unhandled errors.
13. What is [Link], and why is it used?
[Link] is a minimal and flexible web application framework for [Link] that provides a set of
robust features for web and mobile applications. It simplifies the creation of web servers and
APIs by providing built-in middleware, routing, and easy handling of HTTP requests.
14. How do you create a simple [Link] application?
const express = require('express');
const app = express();
[Link]('/', (req, res) => {
[Link]('Hello World!');
});
[Link](3000, () =>
{
[Link]('Server running on port 3000');
});
15. What is the difference between [Link]() and [Link]() in [Link]?
a. [Link](): Used to register middleware functions that are executed for every
request to the server.
b. [Link](): Used to define a route that responds to GET requests.
16. Explain how routing works in [Link].
Routing in [Link] involves mapping HTTP requests to specific URL paths. The app
responds to different HTTP methods (GET, POST, PUT, DELETE) and routes based on
these paths.
[Link]('/users', (req, res) => { [Link]('User List'); });
17. What is Middleware in [Link]? How does it work?
Middleware functions are functions that execute during the lifecycle of a request to an
[Link] app. Middleware can modify the request, response, and pass control to the next
middleware using next().
18. How does Error Handling work in [Link]?
Error-handling middleware has four arguments: (err, req, res, next). It captures any errors
thrown in the app and sends appropriate responses.
[Link]((err, req, res, next) => {
[Link](500).send('Something broke!'); });
19. What is the [Link]() middleware, and when do you use it?
The [Link]() middleware parses incoming requests with JSON payloads and is based
on a body-parser. It's used when you expect JSON data in requests.
20. What are Route Parameters and Query Parameters in [Link]?
a. Route parameters are part of the URL and are defined using :paramName.
Example: /users/:id
b. Query parameters are passed in the URL after a ?. Example: /users?id=123
21. How do you secure an [Link] application?
Use strategies like:
a. Enabling HTTPS
b. Using security headers with helmet
c. Implementing rate limiting with express-rate-limit
d. Validating user inputs
22. Explain the role of [Link]() vs. [Link]() in [Link].
a. [Link](): Sends a response in any format (string, buffer, or object).
b. [Link](): Sends a JSON response, automatically setting the Content-Type
header to application/json. i.
23. What are some commonly used third-party middleware in [Link]?
Some popular middleware includes:
a. body-parser: Parses request bodies.
b. morgan: Logs HTTP requests.
c. cors: Enables Cross-Origin Resource Sharing.
24. What is the difference between PUT and PATCH requests in HTTP?
a. PUT Request: Used to update a resource completely. When you send a PUT
request, the entire resource is replaced with the new data provided. It is
idempotent, meaning multiple PUT requests with the same data will yield the
same result.
b. PATCH Request: Used to partially update a resource. When you send a PATCH
request, only the fields that are included in the request will be updated, leaving
the rest of the resource unchanged.
c. Example:
d. PUT /users/1 with the body { "name": "John", "age": 25 } will
replace the entire user resource.
e. PATCH /users/1 with the body { "age": 26 } will update only the age field while
keeping the name unchanged.
25. What does CRUD stand for, and how is it implemented in [Link]?
CRUD stands for Create, Read, Update, Delete—the four basic operations for
managing data.
Example CRUD operations:
a. Create: POST /users - Adds a new user
b. Read: GET /users/:id - Retrieves a user by ID
c. Update: PUT /users/:id - Updates an existing user
d. Delete: DELETE /users/:id - Deletes a user by ID
26. What is the status code for a successful POST operation, and why is it
important? The correct status code for a successful POST operation is 201
(Created). It indicates that a new resource has been successfully created on the
server.
27. How do you handle validation and error handling in CRUD operations?
Validation is performed by checking the incoming data before performing any operation.
Error handling is implemented by sending appropriate error responses using [Link]()
with codes like 400 (Bad Request), 404 (Not Found), or 500 (Internal Server Error).
Example:
[Link]('/users', (req, res) => {
if (![Link]) {
return [Link](400).send('Name is required');
}
// Logic to save user [Link](201).send('User created
successfully');});
28. What are the best practices for building RESTful APIs with CRUD operations?
a. Use appropriate HTTP methods (GET, POST, PUT, PATCH, DELETE)
b. Return correct HTTP status codes (200, 201, 204, 404, 500)
c. Validate incoming data before performing operations
d. Implement proper error handling and return descriptive error messages
e. Secure your endpoints with authentication/authorization mechanisms
29. What are the potential performance issues in a CRUD API, and how can you
address them?
Performance issues in CRUD APIs can arise from:
a. Slow database queries
b. Handling large data sets
c. Lack of caching Solutions include optimizing database queries, implementing
caching, and paginating large responses.
30. What is CORS (Cross-Origin Resource Sharing)?
a. CORS is a security feature implemented by web browsers to restrict web pages
from making requests to a different domain (origin) than the one that served the
web page. It allows or restricts cross-origin requests to ensure that web
applications can only access resources from the same origin, unless explicitly
permitted by the server.
31. Install the cors package:
First, you need to install the cors middleware package, which simplifies handling CORS in
Express.
npm install cors
a. Configure cors in your Express app:
After installing, you can use the cors middleware to allow cross-origin requests.
Below
const express = require('express');
const cors = require('cors');
const app = express();
[Link](cors());
const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});
b. This setup will allow all domains to make requests to your Express server.
32. What is JWT (JSON Web Token) and how is it used in [Link]?
a. JWT (JSON Web Token) is an open standard (RFC 7519) for securely
transmitting information between parties as a JSON object. It is often used for
authentication and authorization purposes in web applications.
b. A JWT consists of three parts:
Header: Contains the algorithm used for signing the token (e.g., HMAC SHA256) and the
token type (JWT).
Payload: Contains the claims, which are statements about the entity (user) and additional
metadata (e.g., user ID, expiration time).
Signature: Created by encoding the header and payload, then signing that string using a
secret key.
33. What is MongoDB?
MongoDB is a NoSQL, document-oriented database that stores data in
JSON-like format called BSON (Binary JSON). It is designed to handle large amounts of
unstructured data.
34. Explain the difference between SQL and NoSQL databases.
SQL databases are relational, table-based, and use structured query language for defining
and manipulating data.
NoSQL databases are non-relational, flexible in schema design, and designed for
distributed data storage.
35. How does the MongoDB architecture work?
MongoDB uses a document-based model where data is stored in collections of BSON
documents. It supports replication, horizontal scaling through sharding, and allows querying
through an expressive query language.
36. What is Aggregation in MongoDB?
Aggregation is a way to process a large number of documents in a collection by passing them
through different stages, such as filtering, grouping, sorting, and transforming the data.
37. What is bcrypt, and why is it used in [Link] authentication?
bcrypt is a popular password-hashing library used to securely store passwords in the database.
Instead of storing raw (plain-text) passwords, bcrypt converts them into hashed (encrypted)
strings so even if your database is hacked, attackers cannot see original passwords.
38. What is [Link]() and why is it important?
[Link]() is used to compare a plain-text password with a hashed password stored in
the database.
39. What is a Mongoose Schema? Why do we use it?
A Mongoose Schema defines the structure, data types, and validation rules for documents
inside a MongoDB collection.
const userSchema = new [Link]({
name: String,
email: { type: String, required: true },
age: Number
});
40. How do you add validation to a Mongoose Schema?
const userSchema = new [Link]({
name: { type: String, required: true, minlength: 3 },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18 }
});
✅
Types of validations:
✅
required
✅
unique
✅
min, max
✅
match (regex)
Custom validations