Node.js Interview Questions and Answers

Practice every question in this topic using expandable answers and interview tips. Answer aloud first, then open the explanation.

Back to the complete interview hub

Read question Answer aloud Review
Q1. What is Node.js? [Easy]

Answer: Node.js is an open-source, cross-platform JavaScript runtime environment built on Google's V8 JavaScript engine. It allows developers to run JavaScript outside the browser and is commonly used for building scalable server-side applications, REST APIs, real-time applications, and microservices.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q2. What are the key features of Node.js? [Easy]

Answer: Node.js is asynchronous, event-driven, non-blocking, lightweight, fast due to the V8 engine, highly scalable, cross-platform, and supports a rich package ecosystem through npm.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q3. Why is Node.js single-threaded? [Easy]

Answer: Node.js uses a single-threaded event loop to efficiently handle many concurrent requests. Instead of creating a new thread for each request, it delegates I/O operations to the operating system or thread pool, making it highly scalable.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q4. What is the Event Loop in Node.js? [Medium]

Answer: The Event Loop is the core mechanism that allows Node.js to perform non-blocking asynchronous operations. It continuously checks for completed tasks and executes their callbacks when the call stack becomes empty.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q5. What is npm? [Medium]

Answer: npm (Node Package Manager) is the default package manager for Node.js. It is used to install, update, manage, and publish JavaScript packages and project dependencies.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q6. What is package.json? [Easy]

Answer: package.json is the configuration file of a Node.js project. It contains project metadata, scripts, dependencies, devDependencies, version information, and other project settings.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q7. What is the difference between dependencies and devDependencies? [Medium]

Answer: dependencies are packages required for running the application in production, while devDependencies are only needed during development, such as testing frameworks, build tools, and linters.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q8. What is the difference between CommonJS and ES Modules? [Medium]

Answer: CommonJS uses require() and module.exports for importing and exporting modules. ES Modules use import and export syntax, support static analysis, and are the modern JavaScript module system.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q9. How do you create a simple HTTP server in Node.js? [Medium]

Answer: A basic HTTP server is created using the built-in http module. The createServer() method creates a server that listens for incoming requests and sends responses using the request and response objects.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q10. What are the advantages of using Node.js? [Medium]

Answer: Node.js provides high performance, scalability, asynchronous processing, fast API development, real-time communication support, code sharing between frontend and backend, and a large open-source ecosystem.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q11. What are modules in Node.js? [Medium]

Answer: Modules are reusable blocks of code that encapsulate related functionality. Node.js provides built-in modules such as fs, http, path, os, and events, and developers can also create custom modules or install third-party modules using npm.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q12. What is the require() function in Node.js? [Medium]

Answer: The require() function is used in the CommonJS module system to import built-in, third-party, or custom modules into a Node.js application. Once loaded, modules are cached to improve performance.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q13. What is module caching in Node.js? [Medium]

Answer: When a module is loaded for the first time using require(), Node.js stores it in memory. Subsequent calls to require() return the cached module instead of loading it again, improving application performance.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q14. What is the File System (fs) module? [Medium]

Answer: The fs module is a built-in Node.js module used to interact with the file system. It supports creating, reading, updating, deleting, copying, renaming files, and working with directories using both synchronous and asynchronous methods.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q15. What is the difference between synchronous and asynchronous file operations? [Medium]

Answer: Synchronous operations block the execution of the program until the task completes. Asynchronous operations execute in the background without blocking the event loop, making them more suitable for production applications.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q16. What are Streams in Node.js? [Hard]

Answer: Streams are objects that allow data to be processed piece by piece instead of loading the entire data into memory. This improves performance and memory efficiency when handling large files or network data.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q17. What are the different types of Streams in Node.js? [Hard]

Answer: Node.js provides four types of streams: Readable streams for reading data, Writable streams for writing data, Duplex streams for both reading and writing, and Transform streams that modify data while reading or writing.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q18. What is a Buffer in Node.js? [Hard]

Answer: A Buffer is a global object used to handle binary data directly in memory. Buffers are commonly used when working with files, TCP streams, images, videos, and network protocols.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q19. What is the Path module in Node.js? [Medium]

Answer: The path module provides utilities for working with file and directory paths. Common methods include path.join(), path.resolve(), path.basename(), path.dirname(), and path.extname().

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q20. What is the EventEmitter class in Node.js? [Medium]

Answer: EventEmitter is a core Node.js class that enables event-driven programming. It allows objects to emit named events and register listeners using methods such as on(), once(), emit(), and removeListener(). It is widely used in Node.js core modules and custom applications.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q21. What is Express.js? [Medium]

Answer: Express.js is a fast, lightweight, and flexible web framework built on top of Node.js. It simplifies server-side development by providing routing, middleware, request handling, response handling, template engine support, and REST API development.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q22. What is middleware in Express.js? [Medium]

Answer: Middleware is a function that executes during the request-response cycle. It has access to the request object (req), response object (res), and the next() function. Middleware is commonly used for authentication, logging, validation, error handling, parsing request bodies, and modifying requests or responses.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q23. What is the purpose of the next() function in Express? [Medium]

Answer: The next() function passes control to the next middleware or route handler in the middleware chain. If next() is not called (and no response is sent), the request will remain pending.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q24. What is routing in Express.js? [Medium]

Answer: Routing is the process of defining how an application responds to client requests for specific URLs and HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q25. What are req and res objects in Express? [Medium]

Answer: The req (request) object contains information sent by the client, including parameters, query strings, headers, cookies, and request body. The res (response) object is used to send data, status codes, JSON responses, files, or redirects back to the client.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q26. What is a REST API? [Medium]

Answer: A REST API (Representational State Transfer) is an architectural style for building web services. It uses HTTP methods such as GET, POST, PUT, PATCH, and DELETE to perform operations on resources and typically exchanges data in JSON format.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q27. Explain CRUD operations in REST APIs. [Medium]

Answer: CRUD stands for Create, Read, Update, and Delete. These operations typically map to HTTP methods: POST for Create, GET for Read, PUT or PATCH for Update, and DELETE for Delete.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q28. How do you handle errors in Express.js? [Hard]

Answer: Errors can be handled using custom error-handling middleware with the signature (err, req, res, next). This middleware should be registered after all routes and should return appropriate HTTP status codes and error messages. Asynchronous route handlers should forward errors using next(err) or use try...catch with async/await.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q29. What are environment variables and why are they used? [Medium]

Answer: Environment variables store configuration values outside the application code, such as database credentials, API keys, ports, and secret keys. They improve security and make applications easier to configure across different environments like development, testing, and production.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q30. What are CORS, Morgan, and Helmet in Express.js? [Hard]

Answer: CORS (Cross-Origin Resource Sharing) allows controlled access to resources from different origins. Morgan is a middleware used for HTTP request logging. Helmet is a security middleware that sets various HTTP headers to help protect Express applications from common web vulnerabilities.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q31. What is authentication and authorization? [Hard]

Answer: Authentication is the process of verifying the identity of a user, such as logging in with an email and password. Authorization determines what an authenticated user is allowed to access or perform based on roles and permissions. Authentication happens before authorization.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q32. What is JWT (JSON Web Token)? [Hard]

Answer: JWT is a compact, URL-safe token used for securely transmitting information between a client and a server. A JWT consists of three parts: Header, Payload, and Signature. After successful authentication, the server generates a JWT, which the client sends with subsequent requests for authorization.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q33. How does JWT authentication work in Node.js? [Hard]

Answer: After a user logs in successfully, the server validates the credentials and generates a signed JWT. The client stores the token, usually in an HTTP-only cookie or Authorization header. For protected routes, the server verifies the token before granting access to resources.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q34. What is the difference between Sessions and JWT? [Medium]

Answer: Sessions store user information on the server and identify users using a session ID stored in a cookie. JWT stores user information inside the signed token itself, making it stateless and easier to scale across multiple servers.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q35. What are cookies in Node.js? [Medium]

Answer: Cookies are small pieces of data stored in the user's browser. They are commonly used to store session identifiers, authentication tokens, user preferences, and tracking information. Express applications often use the cookie-parser middleware to read cookies.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q36. Why should passwords be hashed before storing them? [Hard]

Answer: Passwords should never be stored in plain text because they can be exposed if the database is compromised. Hashing algorithms such as bcrypt securely convert passwords into irreversible hashes, protecting user credentials even if the database is leaked.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q37. What is bcrypt? [Hard]

Answer: bcrypt is a popular Node.js library used to securely hash passwords. It automatically generates a random salt and applies multiple hashing rounds, making brute-force attacks significantly more difficult.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q38. What is OAuth? [Hard]

Answer: OAuth is an authorization framework that allows users to grant limited access to their resources without sharing their passwords. It is commonly used for 'Login with Google', 'Login with GitHub', and other third-party authentication providers.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q39. What is rate limiting and why is it important? [Hard]

Answer: Rate limiting restricts the number of requests a client can make within a specified time period. It protects applications from brute-force attacks, denial-of-service attacks, API abuse, and excessive server load. Express applications commonly implement rate limiting using express-rate-limit.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q40. What are some Node.js security best practices? [Hard]

Answer: Use HTTPS, validate and sanitize user input, hash passwords with bcrypt, implement JWT or secure sessions, use Helmet for secure HTTP headers, enable CORS only for trusted origins, apply rate limiting, keep dependencies updated, store secrets in environment variables, avoid exposing sensitive information in error messages, and follow the principle of least privilege.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q41. How do you connect a Node.js application to a database? [Medium]

Answer: Node.js connects to databases using database drivers or Object-Relational/Object-Document Mappers (ORM/ODM). For MongoDB, developers commonly use Mongoose. For MySQL and PostgreSQL, libraries such as mysql2, pg, Sequelize, or TypeORM are widely used. Connection credentials are typically stored in environment variables.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q42. What is MongoDB? [Medium]

Answer: MongoDB is a NoSQL document database that stores data in flexible JSON-like BSON documents instead of tables and rows. It is schema-flexible, scalable, and widely used with Node.js applications.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q43. What is Mongoose? [Medium]

Answer: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides schemas, models, validation, middleware, hooks, and helper methods for interacting with MongoDB in a structured way.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q44. What is Sequelize? [Hard]

Answer: Sequelize is a promise-based ORM for Node.js that supports relational databases such as MySQL, PostgreSQL, MariaDB, Microsoft SQL Server, and SQLite. It simplifies database operations through models, associations, migrations, validations, and transactions.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q45. What is the difference between an ORM and an ODM? [Medium]

Answer: An ORM (Object-Relational Mapper) maps objects to relational database tables and is used with SQL databases such as MySQL and PostgreSQL. An ODM (Object Document Mapper) maps objects to documents in NoSQL databases such as MongoDB.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q46. What are database transactions and why are they important? [Hard]

Answer: A transaction groups multiple database operations into a single unit of work. It follows the ACID principles (Atomicity, Consistency, Isolation, Durability). If any operation fails, the transaction can be rolled back to maintain data integrity.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q47. What is database indexing? [Medium]

Answer: A database index is a data structure that improves query performance by allowing faster data retrieval. While indexes speed up read operations, they also consume additional storage and can slightly slow down insert, update, and delete operations.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q48. How do you implement pagination in a Node.js API? [Medium]

Answer: Pagination is commonly implemented using limit and offset (or skip and limit in MongoDB). Clients send page number and page size, and the server returns only the requested subset of records along with metadata such as total records and total pages.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q49. What is the MongoDB Aggregation Pipeline? [Hard]

Answer: The Aggregation Pipeline processes documents through multiple stages such as $match, $group, $sort, $project, $lookup, and $limit. It is used for filtering, grouping, joining, transforming, and analyzing data efficiently.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q50. What are some database best practices for Node.js applications? [Hard]

Answer: Use connection pooling, parameterized queries to prevent SQL injection, proper indexing, pagination for large datasets, transactions for critical operations, database validation, optimized queries, regular backups, environment variables for credentials, and avoid unnecessary database calls by caching frequently accessed data.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q51. What is Redis and why is it used with Node.js? [Hard]

Answer: Redis is an in-memory key-value data store commonly used as a cache, session store, and message broker. In Node.js applications, Redis improves performance by caching frequently accessed data, reducing database queries, storing user sessions, implementing rate limiting, and supporting real-time features such as pub/sub messaging.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q52. What is clustering in Node.js? [Hard]

Answer: Clustering allows a Node.js application to create multiple worker processes that share the same server port. This enables the application to utilize multiple CPU cores, improving scalability, availability, and performance for handling large numbers of concurrent requests.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q53. What are Worker Threads in Node.js? [Hard]

Answer: Worker Threads enable Node.js to execute CPU-intensive tasks in separate threads without blocking the main event loop. They are useful for image processing, encryption, compression, mathematical computations, and other heavy operations.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q54. What is the difference between Worker Threads and Child Processes? [Hard]

Answer: Worker Threads run within the same Node.js process and can efficiently share memory. Child Processes create entirely separate Node.js processes with independent memory spaces, making them suitable for running external programs or isolating workloads.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q55. What is PM2 and why is it used? [Hard]

Answer: PM2 is a production process manager for Node.js applications. It provides automatic restarts, process monitoring, load balancing, clustering, log management, zero-downtime deployments, and startup script generation, making applications more reliable in production.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q56. Why is Docker commonly used with Node.js applications? [Medium]

Answer: Docker packages a Node.js application along with its dependencies into a portable container. This ensures consistent environments across development, testing, and production while simplifying deployment, scaling, and infrastructure management.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q57. What are Winston and Morgan in Node.js? [Medium]

Answer: Morgan is middleware used for logging HTTP requests in Express applications. Winston is a flexible logging library used for application logging, supporting multiple log levels, log files, remote logging services, and custom transports.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q58. How can you optimize the performance of a Node.js application? [Hard]

Answer: Performance can be improved by using asynchronous programming, caching with Redis, database indexing, connection pooling, compression middleware, pagination, efficient queries, clustering, Worker Threads for CPU-intensive tasks, load balancing, minimizing synchronous operations, and monitoring application performance regularly.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q59. What is CI/CD and how does it help Node.js applications? [Hard]

Answer: CI/CD stands for Continuous Integration and Continuous Deployment (or Delivery). CI automatically builds and tests code whenever changes are committed, while CD automates deployment to staging or production environments. This reduces manual errors, speeds up releases, and improves software quality.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Q60. What are the best practices for developing production-ready Node.js applications? [Hard]

Answer: Follow a modular project structure, use async/await, implement centralized error handling, validate and sanitize user input, store secrets in environment variables, hash passwords with bcrypt, use JWT or secure sessions, enable HTTPS, implement logging and monitoring, write unit and integration tests, optimize database queries, use caching where appropriate, keep dependencies updated, and follow security and coding standards.

Interview tip: Define it clearly, give a small example, and mention one practical use or limitation.

Study checklist

  1. Explain the answer without reading.
  2. Write one small example.
  3. Compare framework or database version differences in official documentation.

Node.js Interview Questions and Answers

Practice one question at a time. Read the question, answer aloud, then compare your explanation with the answer.

← Back to the complete interview hub

Study method: define the concept, give a small example, and mention one practical use or limitation.

Q1. What is Node.js?

Easy

Answer: Node.js is an open-source, cross-platform JavaScript runtime environment built on Google's V8 JavaScript engine. It allows developers to run JavaScript outside the browser and is commonly used for building scalable server-side applications, REST APIs, real-time applications, and microservices.

Interview tip: Use a short example and connect the answer to real project work.

Q2. What are the key features of Node.js?

Easy

Answer: Node.js is asynchronous, event-driven, non-blocking, lightweight, fast due to the V8 engine, highly scalable, cross-platform, and supports a rich package ecosystem through npm.

Interview tip: Use a short example and connect the answer to real project work.

Q3. Why is Node.js single-threaded?

Easy

Answer: Node.js uses a single-threaded event loop to efficiently handle many concurrent requests. Instead of creating a new thread for each request, it delegates I/O operations to the operating system or thread pool, making it highly scalable.

Interview tip: Use a short example and connect the answer to real project work.

Q4. What is the Event Loop in Node.js?

Medium

Answer: The Event Loop is the core mechanism that allows Node.js to perform non-blocking asynchronous operations. It continuously checks for completed tasks and executes their callbacks when the call stack becomes empty.

Interview tip: Use a short example and connect the answer to real project work.

Q5. What is npm?

Medium

Answer: npm (Node Package Manager) is the default package manager for Node.js. It is used to install, update, manage, and publish JavaScript packages and project dependencies.

Interview tip: Use a short example and connect the answer to real project work.

Q6. What is package.json?

Easy

Answer: package.json is the configuration file of a Node.js project. It contains project metadata, scripts, dependencies, devDependencies, version information, and other project settings.

Interview tip: Use a short example and connect the answer to real project work.

Q7. What is the difference between dependencies and devDependencies?

Medium

Answer: dependencies are packages required for running the application in production, while devDependencies are only needed during development, such as testing frameworks, build tools, and linters.

Interview tip: Use a short example and connect the answer to real project work.

Q8. What is the difference between CommonJS and ES Modules?

Medium

Answer: CommonJS uses require() and module.exports for importing and exporting modules. ES Modules use import and export syntax, support static analysis, and are the modern JavaScript module system.

Interview tip: Use a short example and connect the answer to real project work.

Q9. How do you create a simple HTTP server in Node.js?

Medium

Answer: A basic HTTP server is created using the built-in http module. The createServer() method creates a server that listens for incoming requests and sends responses using the request and response objects.

Interview tip: Use a short example and connect the answer to real project work.

Q10. What are the advantages of using Node.js?

Medium

Answer: Node.js provides high performance, scalability, asynchronous processing, fast API development, real-time communication support, code sharing between frontend and backend, and a large open-source ecosystem.

Interview tip: Use a short example and connect the answer to real project work.

Q11. What are modules in Node.js?

Medium

Answer: Modules are reusable blocks of code that encapsulate related functionality. Node.js provides built-in modules such as fs, http, path, os, and events, and developers can also create custom modules or install third-party modules using npm.

Interview tip: Use a short example and connect the answer to real project work.

Q12. What is the require() function in Node.js?

Medium

Answer: The require() function is used in the CommonJS module system to import built-in, third-party, or custom modules into a Node.js application. Once loaded, modules are cached to improve performance.

Interview tip: Use a short example and connect the answer to real project work.

Q13. What is module caching in Node.js?

Medium

Answer: When a module is loaded for the first time using require(), Node.js stores it in memory. Subsequent calls to require() return the cached module instead of loading it again, improving application performance.

Interview tip: Use a short example and connect the answer to real project work.

Q14. What is the File System (fs) module?

Medium

Answer: The fs module is a built-in Node.js module used to interact with the file system. It supports creating, reading, updating, deleting, copying, renaming files, and working with directories using both synchronous and asynchronous methods.

Interview tip: Use a short example and connect the answer to real project work.

Q15. What is the difference between synchronous and asynchronous file operations?

Medium

Answer: Synchronous operations block the execution of the program until the task completes. Asynchronous operations execute in the background without blocking the event loop, making them more suitable for production applications.

Interview tip: Use a short example and connect the answer to real project work.

Q16. What are Streams in Node.js?

Hard

Answer: Streams are objects that allow data to be processed piece by piece instead of loading the entire data into memory. This improves performance and memory efficiency when handling large files or network data.

Interview tip: Use a short example and connect the answer to real project work.

Q17. What are the different types of Streams in Node.js?

Hard

Answer: Node.js provides four types of streams: Readable streams for reading data, Writable streams for writing data, Duplex streams for both reading and writing, and Transform streams that modify data while reading or writing.

Interview tip: Use a short example and connect the answer to real project work.

Q18. What is a Buffer in Node.js?

Hard

Answer: A Buffer is a global object used to handle binary data directly in memory. Buffers are commonly used when working with files, TCP streams, images, videos, and network protocols.

Interview tip: Use a short example and connect the answer to real project work.

Q19. What is the Path module in Node.js?

Medium

Answer: The path module provides utilities for working with file and directory paths. Common methods include path.join(), path.resolve(), path.basename(), path.dirname(), and path.extname().

Interview tip: Use a short example and connect the answer to real project work.

Q20. What is the EventEmitter class in Node.js?

Medium

Answer: EventEmitter is a core Node.js class that enables event-driven programming. It allows objects to emit named events and register listeners using methods such as on(), once(), emit(), and removeListener(). It is widely used in Node.js core modules and custom applications.

Interview tip: Use a short example and connect the answer to real project work.

Q21. What is Express.js?

Medium

Answer: Express.js is a fast, lightweight, and flexible web framework built on top of Node.js. It simplifies server-side development by providing routing, middleware, request handling, response handling, template engine support, and REST API development.

Interview tip: Use a short example and connect the answer to real project work.

Q22. What is middleware in Express.js?

Medium

Answer: Middleware is a function that executes during the request-response cycle. It has access to the request object (req), response object (res), and the next() function. Middleware is commonly used for authentication, logging, validation, error handling, parsing request bodies, and modifying requests or responses.

Interview tip: Use a short example and connect the answer to real project work.

Q23. What is the purpose of the next() function in Express?

Medium

Answer: The next() function passes control to the next middleware or route handler in the middleware chain. If next() is not called (and no response is sent), the request will remain pending.

Interview tip: Use a short example and connect the answer to real project work.

Q24. What is routing in Express.js?

Medium

Answer: Routing is the process of defining how an application responds to client requests for specific URLs and HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

Interview tip: Use a short example and connect the answer to real project work.

Q25. What are req and res objects in Express?

Medium

Answer: The req (request) object contains information sent by the client, including parameters, query strings, headers, cookies, and request body. The res (response) object is used to send data, status codes, JSON responses, files, or redirects back to the client.

Interview tip: Use a short example and connect the answer to real project work.

Q26. What is a REST API?

Medium

Answer: A REST API (Representational State Transfer) is an architectural style for building web services. It uses HTTP methods such as GET, POST, PUT, PATCH, and DELETE to perform operations on resources and typically exchanges data in JSON format.

Interview tip: Use a short example and connect the answer to real project work.

Q27. Explain CRUD operations in REST APIs.

Medium

Answer: CRUD stands for Create, Read, Update, and Delete. These operations typically map to HTTP methods: POST for Create, GET for Read, PUT or PATCH for Update, and DELETE for Delete.

Interview tip: Use a short example and connect the answer to real project work.

Q28. How do you handle errors in Express.js?

Hard

Answer: Errors can be handled using custom error-handling middleware with the signature (err, req, res, next). This middleware should be registered after all routes and should return appropriate HTTP status codes and error messages. Asynchronous route handlers should forward errors using next(err) or use try...catch with async/await.

Interview tip: Use a short example and connect the answer to real project work.

Q29. What are environment variables and why are they used?

Medium

Answer: Environment variables store configuration values outside the application code, such as database credentials, API keys, ports, and secret keys. They improve security and make applications easier to configure across different environments like development, testing, and production.

Interview tip: Use a short example and connect the answer to real project work.

Q30. What are CORS, Morgan, and Helmet in Express.js?

Hard

Answer: CORS (Cross-Origin Resource Sharing) allows controlled access to resources from different origins. Morgan is a middleware used for HTTP request logging. Helmet is a security middleware that sets various HTTP headers to help protect Express applications from common web vulnerabilities.

Interview tip: Use a short example and connect the answer to real project work.

Q31. What is authentication and authorization?

Hard

Answer: Authentication is the process of verifying the identity of a user, such as logging in with an email and password. Authorization determines what an authenticated user is allowed to access or perform based on roles and permissions. Authentication happens before authorization.

Interview tip: Use a short example and connect the answer to real project work.

Q32. What is JWT (JSON Web Token)?

Hard

Answer: JWT is a compact, URL-safe token used for securely transmitting information between a client and a server. A JWT consists of three parts: Header, Payload, and Signature. After successful authentication, the server generates a JWT, which the client sends with subsequent requests for authorization.

Interview tip: Use a short example and connect the answer to real project work.

Q33. How does JWT authentication work in Node.js?

Hard

Answer: After a user logs in successfully, the server validates the credentials and generates a signed JWT. The client stores the token, usually in an HTTP-only cookie or Authorization header. For protected routes, the server verifies the token before granting access to resources.

Interview tip: Use a short example and connect the answer to real project work.

Q34. What is the difference between Sessions and JWT?

Medium

Answer: Sessions store user information on the server and identify users using a session ID stored in a cookie. JWT stores user information inside the signed token itself, making it stateless and easier to scale across multiple servers.

Interview tip: Use a short example and connect the answer to real project work.

Q35. What are cookies in Node.js?

Medium

Answer: Cookies are small pieces of data stored in the user's browser. They are commonly used to store session identifiers, authentication tokens, user preferences, and tracking information. Express applications often use the cookie-parser middleware to read cookies.

Interview tip: Use a short example and connect the answer to real project work.

Q36. Why should passwords be hashed before storing them?

Hard

Answer: Passwords should never be stored in plain text because they can be exposed if the database is compromised. Hashing algorithms such as bcrypt securely convert passwords into irreversible hashes, protecting user credentials even if the database is leaked.

Interview tip: Use a short example and connect the answer to real project work.

Q37. What is bcrypt?

Hard

Answer: bcrypt is a popular Node.js library used to securely hash passwords. It automatically generates a random salt and applies multiple hashing rounds, making brute-force attacks significantly more difficult.

Interview tip: Use a short example and connect the answer to real project work.

Q38. What is OAuth?

Hard

Answer: OAuth is an authorization framework that allows users to grant limited access to their resources without sharing their passwords. It is commonly used for 'Login with Google', 'Login with GitHub', and other third-party authentication providers.

Interview tip: Use a short example and connect the answer to real project work.

Q39. What is rate limiting and why is it important?

Hard

Answer: Rate limiting restricts the number of requests a client can make within a specified time period. It protects applications from brute-force attacks, denial-of-service attacks, API abuse, and excessive server load. Express applications commonly implement rate limiting using express-rate-limit.

Interview tip: Use a short example and connect the answer to real project work.

Q40. What are some Node.js security best practices?

Hard

Answer: Use HTTPS, validate and sanitize user input, hash passwords with bcrypt, implement JWT or secure sessions, use Helmet for secure HTTP headers, enable CORS only for trusted origins, apply rate limiting, keep dependencies updated, store secrets in environment variables, avoid exposing sensitive information in error messages, and follow the principle of least privilege.

Interview tip: Use a short example and connect the answer to real project work.

Q41. How do you connect a Node.js application to a database?

Medium

Answer: Node.js connects to databases using database drivers or Object-Relational/Object-Document Mappers (ORM/ODM). For MongoDB, developers commonly use Mongoose. For MySQL and PostgreSQL, libraries such as mysql2, pg, Sequelize, or TypeORM are widely used. Connection credentials are typically stored in environment variables.

Interview tip: Use a short example and connect the answer to real project work.

Q42. What is MongoDB?

Medium

Answer: MongoDB is a NoSQL document database that stores data in flexible JSON-like BSON documents instead of tables and rows. It is schema-flexible, scalable, and widely used with Node.js applications.

Interview tip: Use a short example and connect the answer to real project work.

Q43. What is Mongoose?

Medium

Answer: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides schemas, models, validation, middleware, hooks, and helper methods for interacting with MongoDB in a structured way.

Interview tip: Use a short example and connect the answer to real project work.

Q44. What is Sequelize?

Hard

Answer: Sequelize is a promise-based ORM for Node.js that supports relational databases such as MySQL, PostgreSQL, MariaDB, Microsoft SQL Server, and SQLite. It simplifies database operations through models, associations, migrations, validations, and transactions.

Interview tip: Use a short example and connect the answer to real project work.

Q45. What is the difference between an ORM and an ODM?

Medium

Answer: An ORM (Object-Relational Mapper) maps objects to relational database tables and is used with SQL databases such as MySQL and PostgreSQL. An ODM (Object Document Mapper) maps objects to documents in NoSQL databases such as MongoDB.

Interview tip: Use a short example and connect the answer to real project work.

Q46. What are database transactions and why are they important?

Hard

Answer: A transaction groups multiple database operations into a single unit of work. It follows the ACID principles (Atomicity, Consistency, Isolation, Durability). If any operation fails, the transaction can be rolled back to maintain data integrity.

Interview tip: Use a short example and connect the answer to real project work.

Q47. What is database indexing?

Medium

Answer: A database index is a data structure that improves query performance by allowing faster data retrieval. While indexes speed up read operations, they also consume additional storage and can slightly slow down insert, update, and delete operations.

Interview tip: Use a short example and connect the answer to real project work.

Q48. How do you implement pagination in a Node.js API?

Medium

Answer: Pagination is commonly implemented using limit and offset (or skip and limit in MongoDB). Clients send page number and page size, and the server returns only the requested subset of records along with metadata such as total records and total pages.

Interview tip: Use a short example and connect the answer to real project work.

Q49. What is the MongoDB Aggregation Pipeline?

Hard

Answer: The Aggregation Pipeline processes documents through multiple stages such as $match, $group, $sort, $project, $lookup, and $limit. It is used for filtering, grouping, joining, transforming, and analyzing data efficiently.

Interview tip: Use a short example and connect the answer to real project work.

Q50. What are some database best practices for Node.js applications?

Hard

Answer: Use connection pooling, parameterized queries to prevent SQL injection, proper indexing, pagination for large datasets, transactions for critical operations, database validation, optimized queries, regular backups, environment variables for credentials, and avoid unnecessary database calls by caching frequently accessed data.

Interview tip: Use a short example and connect the answer to real project work.

Q51. What is Redis and why is it used with Node.js?

Hard

Answer: Redis is an in-memory key-value data store commonly used as a cache, session store, and message broker. In Node.js applications, Redis improves performance by caching frequently accessed data, reducing database queries, storing user sessions, implementing rate limiting, and supporting real-time features such as pub/sub messaging.

Interview tip: Use a short example and connect the answer to real project work.

Q52. What is clustering in Node.js?

Hard

Answer: Clustering allows a Node.js application to create multiple worker processes that share the same server port. This enables the application to utilize multiple CPU cores, improving scalability, availability, and performance for handling large numbers of concurrent requests.

Interview tip: Use a short example and connect the answer to real project work.

Q53. What are Worker Threads in Node.js?

Hard

Answer: Worker Threads enable Node.js to execute CPU-intensive tasks in separate threads without blocking the main event loop. They are useful for image processing, encryption, compression, mathematical computations, and other heavy operations.

Interview tip: Use a short example and connect the answer to real project work.

Q54. What is the difference between Worker Threads and Child Processes?

Hard

Answer: Worker Threads run within the same Node.js process and can efficiently share memory. Child Processes create entirely separate Node.js processes with independent memory spaces, making them suitable for running external programs or isolating workloads.

Interview tip: Use a short example and connect the answer to real project work.

Q55. What is PM2 and why is it used?

Hard

Answer: PM2 is a production process manager for Node.js applications. It provides automatic restarts, process monitoring, load balancing, clustering, log management, zero-downtime deployments, and startup script generation, making applications more reliable in production.

Interview tip: Use a short example and connect the answer to real project work.

Q56. Why is Docker commonly used with Node.js applications?

Medium

Answer: Docker packages a Node.js application along with its dependencies into a portable container. This ensures consistent environments across development, testing, and production while simplifying deployment, scaling, and infrastructure management.

Interview tip: Use a short example and connect the answer to real project work.

Q57. What are Winston and Morgan in Node.js?

Medium

Answer: Morgan is middleware used for logging HTTP requests in Express applications. Winston is a flexible logging library used for application logging, supporting multiple log levels, log files, remote logging services, and custom transports.

Interview tip: Use a short example and connect the answer to real project work.

Q58. How can you optimize the performance of a Node.js application?

Hard

Answer: Performance can be improved by using asynchronous programming, caching with Redis, database indexing, connection pooling, compression middleware, pagination, efficient queries, clustering, Worker Threads for CPU-intensive tasks, load balancing, minimizing synchronous operations, and monitoring application performance regularly.

Interview tip: Use a short example and connect the answer to real project work.

Q59. What is CI/CD and how does it help Node.js applications?

Hard

Answer: CI/CD stands for Continuous Integration and Continuous Deployment (or Delivery). CI automatically builds and tests code whenever changes are committed, while CD automates deployment to staging or production environments. This reduces manual errors, speeds up releases, and improves software quality.

Interview tip: Use a short example and connect the answer to real project work.

Q60. What are the best practices for developing production-ready Node.js applications?

Hard

Answer: Follow a modular project structure, use async/await, implement centralized error handling, validate and sanitize user input, store secrets in environment variables, hash passwords with bcrypt, use JWT or secure sessions, enable HTTPS, implement logging and monitoring, write unit and integration tests, optimize database queries, use caching where appropriate, keep dependencies updated, and follow security and coding standards.

Interview tip: Use a short example and connect the answer to real project work.

Quick revision checklist

  1. Explain the answer without reading.
  2. Write one small example.
  3. Review platform or version differences in official documentation.

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.