140 Node.js & Express.js FAQs with Answers
Interview preparation, semester examinations and laboratory viva
Learn Node.js and Express.js from fundamentals to practical backend development, including REST APIs, MongoDB, JWT, Multer and Socket.IO.
Part 1: Node.js Fundamentals
1. What is Node.js?
An open-source, cross-platform JavaScript runtime that executes JavaScript outside the browser.
2. Is Node.js a programming language or framework?
Neither. It is a JavaScript runtime environment.
3. What are the important features of Node.js?
Asynchronous execution, event-driven architecture, non-blocking I/O, V8, cross-platform support and a large npm ecosystem.
4. What is the V8 engine?
Google’s JavaScript engine, which compiles JavaScript into machine code.
5. Why is Node.js used for backend development?
It handles concurrent I/O efficiently and allows JavaScript on both frontend and backend.
6. Is Node.js single-threaded?
JavaScript normally runs on one main thread, while Node.js also uses OS facilities, background threads and worker threads.
7. What is NPM?
Node Package Manager, used to install and manage packages and dependencies.
8. What is NPX?
A command-line tool for executing package commands without a separate global installation.
9. What is package.json?
A file containing project metadata, scripts and dependencies.
10. What is package-lock.json?
A file recording resolved dependency versions for reproducible installations.
11. What is node_modules?
The directory containing installed packages and dependencies.
12. What is REPL?
Read, Evaluate, Print and Loop: an interactive JavaScript execution environment.
13. How do you initialize a Node.js project?
npm init -y
14. How do you execute a Node.js application?
node app.js
15. What is Nodemon?
A development utility that restarts an application when monitored files change. Install with npm install --save-dev nodemon and run npx nodemon app.js.
Part 2: Node.js Modules
16. What is a module?
A reusable unit of code providing specific functionality.
17. What are the types of modules?
Built-in (http, fs, path), local (user-defined files), and third-party (Express, Mongoose, Multer).
18. What is require()?
A CommonJS function for loading modules. Example: const fs = require("fs");
19. What is module.exports?
It exports functions, objects or variables from a CommonJS module.
module.exports = function add(a, b) {
return a + b;
};
20. What is the difference between CommonJS and ES Modules?
CommonJS uses require() and module.exports; ES Modules use import and export. Explicit extensions are .cjs and .mjs respectively.
| CommonJS | ES Modules |
|---|---|
| require() | import |
| module.exports | export |
| .cjs | .mjs |
21. What is the HTTP module?
A built-in module for creating HTTP servers and clients.
22. What is the File System module?
The fs module reads, writes, updates and deletes files.
23. What is the Path module?
Utilities for working with file and directory paths.
24. What is the OS module?
Provides information about the operating system, CPU, memory and network interfaces.
25. What is the Events module?
Provides EventEmitter for registering listeners and emitting events.
Part 3: Asynchronous Programming and Event Handling
26. What is synchronous programming?
Operations execute sequentially, each completing before the next proceeds.
27. What is asynchronous programming?
Other operations can continue while an asynchronous operation is pending.
28. What is blocking and non-blocking I/O?
Blocking I/O waits for completion; non-blocking I/O allows other work to continue. Examples: readFileSync() and readFile().
29. What is the Event Loop?
The mechanism that coordinates asynchronous operations and executes ready callbacks.
30. What is libuv?
A cross-platform library providing the event loop, asynchronous I/O and thread pool support.
31. What is a callback function?
A function passed to another function to be executed at an appropriate time.
32. What is callback hell?
Deeply nested callbacks that make code difficult to read and maintain.
33. What is a Promise?
An object representing eventual completion or failure of an asynchronous operation.
34. What are the states of a Promise?
Pending, fulfilled and rejected.
35. What is async/await?
Syntax for writing Promise-based asynchronous code in a readable manner.
36. What is EventEmitter?
A class for registering event listeners and emitting custom events.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("welcome", () => console.log("Welcome"));
emitter.emit("welcome");
37. What is a Buffer?
An object for storing and manipulating binary data.
38. What are Streams?
Interfaces for processing data incrementally without loading it all into memory.
39. What are the types of Streams?
Readable, Writable, Duplex and Transform.
40. How do you create a simple HTTP server?
Use the built-in http module and createServer().
const http = require("http");
http.createServer((req, res) => {
res.end("Welcome to Node.js");
}).listen(3000);
Part 4: Express.js Fundamentals
41. What is Express.js?
A lightweight, open-source Node.js web framework for web applications and REST APIs.
42. What is the difference between Node.js and Express.js?
Node.js is a runtime; Express is a framework running on Node.js that simplifies routing and HTTP handling.
| Node.js | Express.js |
|---|---|
| Runtime | Web framework |
| Low-level HTTP facilities | Routing and middleware |
| Can run without Express | Runs on Node.js |
43. What are the advantages of Express.js?
Simplified routing, middleware, request and response handling, REST APIs and error handling.
44. How do you install Express.js?
npm install express
45. How do you create a simple Express server?
Create an Express application, define a route and listen on a port.
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Welcome"));
app.listen(3000);
46. What is routing?
Defining how an application responds to specific URLs and HTTP methods.
47. What are req and res?
req represents the incoming request; res represents the outgoing response.
48. What is app.listen()?
Starts the server listening on a specified port.
49. What is res.send()?
Sends an HTTP response containing supported data such as text, HTML or objects.
50. What is res.json()?
Sends a JSON response.
res.json({ name: "Student", course: "Node.js" });
51. What is the difference between res.send() and res.json()?
res.send() supports different response types; res.json() explicitly serializes a value as JSON.
52. What are route parameters?
Named dynamic values in a URL path, such as /students/:id, accessed through req.params.id.
app.get("/students/:id", (req, res) => {
res.send(req.params.id);
});
53. What are query parameters?
Key-value pairs after ? in a URL, accessed through req.query.
54. What is the difference between req.params, req.query and req.body?
They access path parameters, query parameters and parsed request body respectively.
| Property | Purpose |
|---|---|
| req.params | Path parameters |
| req.query | Query parameters |
| req.body | Parsed body |
55. What is Express Router?
A mechanism for creating modular, reusable route handlers.
const router = express.Router();
router.get("/", (req, res) => res.send("Student List"));
app.use("/students", router);
Part 5: Middleware in Express.js
56. What is middleware?
A function with access to the request, response and next middleware function.
57. What is the purpose of middleware?
Authentication, authorization, logging, validation, parsing and error handling.
58. How does middleware work?
Requests pass through registered middleware in order. Each can call next() or terminate the request with a response.
59. What is next()?
Transfers control to the next applicable middleware or route handler.
60. What are the types of middleware?
Application-level, router-level, built-in, third-party and error-handling middleware.
61. What is app.use()?
Registers middleware or mounts routers.
62. What is express.json()?
Built-in middleware for parsing incoming JSON request bodies. app.use(express.json());
63. What is express.urlencoded()?
Middleware for parsing URL-encoded form data. app.use(express.urlencoded({ extended: true }));
64. What is express.static()?
Middleware for serving static files such as images, CSS and JavaScript.
app.use("/uploads", express.static("uploads"));
65. How do you create custom middleware?
Define a function accepting req, res and next, then register it with app.use().
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
66. What is error-handling middleware?
Middleware with four parameters: err, req, res and next.
app.use((err, req, res, next) => {
res.status(500).json({ message: "Internal Server Error" });
});
Part 6: REST API and HTTP Methods
67. What is an API?
Application Programming Interface: enables communication between software applications.
68. What is a REST API?
An interface following REST architectural principles, commonly using HTTP to access resources.
69. What does REST stand for?
Representational State Transfer.
70. What is CRUD?
Create, Read, Update and Delete.
71. What are the commonly used HTTP methods?
GET, POST, PUT, PATCH and DELETE.
| Method | Operation |
|---|---|
| GET | Read |
| POST | Create / submit |
| PUT | Replace |
| PATCH | Partial update |
| DELETE | Delete |
72. What is an API endpoint?
A specific URL through which a client accesses a resource or service, such as /api/students.
73. What are HTTP status codes?
Numeric codes indicating the result of an HTTP request.
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Authentication required or invalid |
| 403 | Forbidden |
| 404 | Not Found |
| 409 | Conflict |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
74. What is JSON?
JavaScript Object Notation, a lightweight text-based data exchange format.
75. What is Postman?
An API development and testing tool for sending requests and examining responses.
76. What is CORS?
Cross-Origin Resource Sharing: a browser-enforced mechanism allowing servers to specify permitted origins.
77. How do you enable CORS?
Install the cors package and register its middleware with the appropriate allowed origin.
const cors = require("cors");
app.use(cors({ origin: "http://localhost:5173" }));
78. What is the difference between GET and POST?
GET retrieves resources and is intended to be read-only and idempotent. POST submits data and may change state.
79. What is the difference between PUT and PATCH?
PUT generally replaces a resource representation; PATCH applies partial modifications.
80. What is a stateless REST API?
Each request contains the information needed for processing without relying on server-side conversational session state.
Part 7: MongoDB and Mongoose
81. What is MongoDB?
A NoSQL document database storing data in BSON documents.
82. What is Mongoose?
An Object Data Modeling (ODM) library for MongoDB and Node.js.
83. What is a collection?
A group of MongoDB documents, analogous to a relational table.
84. What is a document?
A record containing field-value pairs.
85. What is a Mongoose Schema?
Defines document structure, data types and validation rules.
86. What is a Mongoose Model?
A model created from a schema that provides database operation methods.
87. How do you connect Node.js with MongoDB?
Use mongoose.connect() with a MongoDB connection URI.
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/college")
.then(() => console.log("Connected"))
.catch(console.error);
88. How do you define a Mongoose Schema and Model?
Create a mongoose.Schema and pass it to mongoose.model().
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
department: String
});
const Student = mongoose.model("Student", studentSchema);
89. What are commonly used Mongoose methods?
create(), save(), find(), findOne(), findById(), findByIdAndUpdate() and findByIdAndDelete().
90. What is ObjectId?
A 12-byte BSON type commonly used as a unique document identifier.
Part 8: Authentication, Authorization and JWT
91. What is authentication?
Verifying a user’s identity.
92. What is authorization?
Determining whether a user has permission to access a resource or perform an operation.
93. What is the difference between authentication and authorization?
Authentication verifies who you are; authorization verifies what you may do.
94. What is JWT?
JSON Web Token, a compact URL-safe format for transmitting claims, commonly used for authentication.
95. What are the three parts of a signed JWT?
Header, Payload and Signature, separated by dots.
96. How does JWT authentication work?
The server verifies credentials and issues a token. The client sends it with subsequent requests, and the server verifies it and checks permissions.
97. How do you generate a JWT?
Use jwt.sign() with claims, a secret or signing key, and an expiration time.
const jwt = require("jsonwebtoken");
const token = jwt.sign({ id: user._id },
process.env.JWT_SECRET, { expiresIn: "1h" });
98. How do you verify a JWT?
Use jwt.verify() with the appropriate verification key and validation options.
const decoded = jwt.verify(token, process.env.JWT_SECRET);
99. What is a Bearer Token?
An access credential commonly sent in the Authorization header as Bearer followed by the token.
100. What is bcrypt?
A password-hashing algorithm commonly used to securely store passwords.
101. What is the difference between hashing and encryption?
Hashing is designed to be one-way; encryption is reversible using the appropriate key.
102. What is a protected route?
An endpoint requiring authentication and, where applicable, authorization.
103. What is Role-Based Access Control (RBAC)?
Granting permissions based on roles such as Admin, Faculty and Student.
104. Is JWT data encrypted?
Not necessarily. Signed JWT payloads can be decoded; never put passwords in them.
105. What happens when a JWT expires?
The server rejects it; the client must authenticate again or use a valid refresh-token mechanism.
Part 9: File Uploading Using Multer
106. What is Multer?
Express middleware for multipart/form-data, primarily file uploads.
107. How do you install Multer?
npm install multer
108. What are the storage options in Multer?
Disk Storage and Memory Storage.
109. What is upload.single()?
Handles a single file uploaded through a specified form field.
app.post("/upload", upload.single("logo"), (req, res) => {
if (!req.file) return res.status(400).json({ message: "File required" });
res.json({ filename: req.file.filename });
});
110. What is upload.array()?
Handles multiple files associated with the same form field.
111. What is req.file?
Information about a single uploaded file, such as its name, size and MIME type.
112. What is req.files?
Information about multiple uploaded files.
113. What is fileFilter?
Controls which uploads are accepted. Secure validation should also inspect actual file contents where appropriate.
114. How do you restrict uploaded file size?
Configure Multer limits.fileSize in bytes.
const upload = multer({ limits: { fileSize: 2 * 1024 * 1024 } });
115. How do you access uploaded images from the frontend?
Serve public images through express.static() and access their URLs.
app.use("/uploads", express.static("uploads"));
Part 10: Socket.IO and Real-Time Communication
116. What is Socket.IO?
A JavaScript library for real-time, bidirectional, event-based communication.
117. What is WebSocket?
A protocol enabling persistent full-duplex client-server communication.
118. What is the difference between HTTP and WebSocket?
HTTP normally uses request-response exchanges; WebSocket enables persistent bidirectional communication.
119. What is the difference between WebSocket and Socket.IO?
WebSocket is a protocol; Socket.IO is a library providing events, reconnection, broadcasting and fallback transport support.
120. How do you install Socket.IO?
npm install socket.io
121. What is socket.emit()?
Sends an event to the connected peer.
122. What is socket.on()?
Registers a listener for an event.
123. What is io.emit()?
Broadcasts an event to all connected clients in the relevant namespace.
124. What is socket.broadcast.emit()?
Sends an event to other connected clients, excluding the originating socket.
125. How can Socket.IO be used for real-time logo updates?
After an administrator uploads a logo, broadcast the new URL so connected clients update their display without refreshing.
io.emit("logoUpdated", { logoUrl: "/uploads/new-logo.png" });
Part 11: Application Architecture, Security and Deployment
126. What is MVC architecture?
Model-View-Controller separates data management, presentation and request handling.
127. What is the purpose of a Controller?
Handles requests, coordinates application logic and generates responses.
128. What is the purpose of a Model?
Represents application data and provides database interaction functionality.
129. What is a .env file?
A file for configuring environment variables such as database URLs, ports and secrets.
130. What is dotenv?
A package that loads .env variables into process.env. require("dotenv").config();
131. Why should sensitive information not be hardcoded?
Secrets may be exposed through source repositories or application distribution.
132. What is Helmet?
Middleware that helps secure Express applications by configuring HTTP security headers.
133. What is rate limiting?
Restricting the number of requests a client can make within a specified period.
134. What is input validation?
Checking incoming data against expected types, formats, lengths and business rules.
135. What is API versioning?
Introducing API changes while maintaining compatibility with existing clients, for example /api/v1/students.
136. What is the difference between dependencies and devDependencies?
Dependencies are needed for application operation; devDependencies are primarily used for development.
137. What is process.env?
The Node.js object for accessing environment variables.
138. What is PM2?
A process manager for running, monitoring and managing Node.js applications.
139. What is the MERN Stack?
MongoDB, Express.js, React.js and Node.js.
140. What are real-world applications of Node.js and Express.js?
E-commerce, student management, feedback systems, chat, dashboards, streaming and mobile application APIs.
25 Important Laboratory Viva Questions
- What is Node.js, and why is it used?
- What is the difference between Node.js and Express.js?
- Explain the Event Loop.
- What is asynchronous programming?
- What is middleware?
- What is the purpose of next()?
- Differentiate req.params, req.query and req.body.
- What is a REST API?
- Explain CRUD and HTTP methods.
- Differentiate MongoDB and Mongoose.
- Differentiate Schema and Model.
- How do you implement a user registration API?
- Differentiate authentication and authorization.
- What is JWT and how does it work?
- What are the three parts of a signed JWT?
- How do you protect an API using JWT middleware?
- How do you implement Admin Role-Based Access Control?
- What is bcrypt and why is it used?
- How do you retrieve authenticated user profile details?
- What is CORS and why is it required?
- What is Multer and how does it work?
- What is the purpose of express.static()?
- What is Socket.IO?
- Differentiate socket.emit() and io.emit().
- How do you implement real-time logo updates using Socket.IO?
Total coverage: 140 FAQs across 11 topics and 25 laboratory viva questions. Code snippets are illustrative and may require surrounding application setup.







