{jsonbody.com}

Top 100 Node.js Interview Questions and Answers

Prepare for your next backend interview with our comprehensive list of top 100 Node.js interview questions and expert answers.

Q1. What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome's V8 engine that executes JS code server-side.

Q2. Why is Node.js single-threaded?

Node.js uses a single-threaded model for event looping to prevent concurrency and race issues, offloading heavy I/O tasks to libuv worker threads.

Q3. Explain the concept of Event Loop in Node.js.

The Event Loop allows Node.js to perform non-blocking I/O operations by executing callbacks from different phases (timers, poll, check, close).

Q4. What is NPM?

NPM (Node Package Manager) is the default package manager for Node.js used to install, share, and manage project dependencies.

Q5. What are modules in Node.js?

Modules are encapsulated blocks of code that can be imported and exported using CommonJS (require) or ES modules (import/export).

Q6. What is package.json?

package.json is the central metadata file defining project dependencies, scripts, versioning, and configuration details.

Q7. What is middleware in Express.js?

Middleware functions have access to request (req), response (res), and the next function in the request-response lifecycle.

Q8. What is the difference between dependencies and devDependencies?

Dependencies are required for production execution, whereas devDependencies are strictly needed during development and testing.

Q9. How does Node.js handle concurrency?

Through non-blocking asynchronous APIs, callback queues, promises, and the underlying event loop managed by libuv.

Q10. What is libuv?

libuv is a multi-platform C library providing asynchronous I/O, event loops, file system operations, and thread pools to Node.js.

Q11. What are Streams in Node.js?

Streams are objects that let you read data or write data continuously in chunks, making memory management highly efficient.

Q12. Name the types of streams available in Node.js.

Readable, Writable, Duplex, and Transform streams.

Q13. What is EventEmitter in Node.js?

EventEmitter is a core module that facilitates custom event-driven programming through emitter.on() and emitter.emit().

Q14. What is callback hell?

Callback hell refers to deeply nested asynchronous callbacks that make code unreadable and hard to maintain.

Q15. How do you avoid callback hell?

By using Promises, async/await syntax, or modularizing code into smaller named functions.

Q16. What is the difference between process.nextTick() and setImmediate()?

process.nextTick() executes callbacks immediately at the end of the current operation, before the event loop continues. setImmediate() queues callbacks for the check phase.

Q17. What is REPL in Node.js?

REPL stands for Read, Eval, Print, and Loop, providing an interactive shell environment to test JavaScript expressions.

Q18. What is cluster module used for?

The cluster module allows creation of child processes (workers) sharing the same server port to utilize multi-core CPUs.

Q19. What is the role of package-lock.json?

It locks down the exact dependency tree versions installed to ensure consistent builds across different machines.

Q20. Explain Passport.js in Node.js.

Passport is authentication middleware for Node.js supporting strategies like local login, JWT, OAuth, and Google/Facebook login.

Q21. What is JWT?

JSON Web Token is an open standard for securely transmitting information between parties as a JSON object.

Q22. How do you handle security vulnerabilities in Node packages?

By running 'npm audit', updating outdated packages, and avoiding malicious untrusted packages.

Q23. What is CORS in Express?

Cross-Origin Resource Sharing is a security mechanism allowing restricted resources on a web page to be requested from another domain.

Q24. What is PM2?

PM2 is a production process manager for Node.js with built-in load balancing, process monitoring, and auto-restart capabilities.

Q25. What is a Buffer class?

Buffers are global objects used to handle binary data directly in memory outside the V8 heap.

Q26. How do you read command-line arguments in Node.js?

Using the process.argv array.

Q27. What is asynchronous vs synchronous programming?

Asynchronous code runs non-blocking tasks concurrently via callbacks/promises, while synchronous code blocks execution sequentially.

Q28. What is socket.io?

A library enabling real-time, bidirectional, and event-based communication between web clients and servers.

Q29. What is Mongoose?

An ODM (Object Data Modeling) library for MongoDB and Node.js providing schema validation and query building.

Q30. How do you connect Node.js to MySQL?

Using database drivers/packages like 'mysql2' or ORMs like Sequelize/Prisma.

Q31. What is Sequelize?

A promise-based Node.js ORM for SQL databases like PostgreSQL, MySQL, SQLite, and Microsoft SQL Server.

Q32. What is Prisma?

A next-generation modern ORM for Node.js and TypeScript supporting type-safe database queries.

Q33. How do you handle environment variables securely?

Using the 'dotenv' package to load variables from a .env file into process.env.

Q34. What is lodash?

A popular utility library providing helpful functional programming helpers for arrays, objects, and strings.

Q35. What is Axios?

A promise-based HTTP client used to make requests from node or browser environments.

Q36. What is Nodemon?

A development utility tool that automatically restarts the Node application when file changes are detected.

Q37. What is Helmet in Express?

Security middleware that helps secure Express apps by setting various HTTP headers.

Q38. What is Morgan?

An HTTP request logger middleware for Node.js.

Q39. What is Express validator?

A set of express-middleware wrappers for validator.js to validate request body parameters easily.

Q40. Explain error handling middleware in Express.

A middleware function taking four arguments instead of three: (err, req, res, next).

Q41. What is clustering load balancing?

Distributing incoming server traffic across multiple CPU worker instances to maximize performance.

Q42. What is the difference between spawn and fork in child_process?

spawn streams output data continuously without creating a new V8 instance, while fork creates a specialized child process instance with an IPC communication channel.

Q43. What is child_process module?

A built-in module allowing Node.js to spawn system shell processes and run external commands.

Q44. How do you manage memory leaks in Node.js?

Using profiling tools like Chrome DevTools, heap snapshots, and checking uncleaned event listeners or global variables.

Q45. What is V8 engine?

Google's open-source high-performance JavaScript and WebAssembly engine written in C++.

Q46. What is garbage collection in Node.js?

An automated memory management process in V8 that cleans up unused unreferenced objects to free up RAM.

Q47. What is package versioning (SemVer)?

Semantic Versioning follows Major.Minor.Patch format (e.g., 1.4.2) indicating breaking changes, features, and bug fixes.

Q48. What is npm ci?

A command optimized for clean automated CI/CD builds that installs dependencies directly from package-lock.json.

Q49. What is unit testing in Node.js?

Testing individual functions or modules using frameworks like Mocha, Jest, or Chai.

Q50. What is Supertest?

An HTTP assertion testing library commonly used alongside Mocha/Jest to test Express API endpoints.

Q51. What is TypeScript in Node.js?

A strongly typed superset of JavaScript that compiles down to plain JavaScript, adding static typing.

Q52. How do you transpile TypeScript in Node?

Using tools like 'tsc', 'ts-node', or bundlers like SWC and esbuild.

Q53. What is gRPC?

A high-performance RPC framework developed by Google enabling fast microservice communication using Protocol Buffers.

Q54. What are WebSockets?

A communications protocol providing full-duplex communication channels over a single TCP connection.

Q55. What is Redis and how is it used in Node?

An in-memory data store used for caching, session management, and pub/sub message brokering.

Q56. What is rate limiting?

Limiting the number of requests a user can make to an API within a specified timeframe to prevent DDoS attacks.

Q57. What is API throttling?

Controlling the rate of API data transmission to regulate traffic flow.

Q58. What is sharding in databases?

A database architecture pattern splitting large tables across multiple database instances.

Q59. What is connection pooling?

Maintaining a cache of active database connections to reuse for upcoming requests instead of opening new ones each time.

Q60. What is a memory leak?

An unintended retention of objects in memory that are no longer needed by the application.

Q61. What is PM2 cluster mode?

A mode allowing PM2 to scale the Node app across all available CPUs without modifying code.

Q62. What is process.env?

An object containing user environment variables associated with the current running process.

Q63. How do you read files asynchronously in Node.js?

Using fs.readFile() or fs/promises readFile method.

Q64. What is fs.existsSync?

A synchronous method to check whether a given file path exists on the disk.

Q65. What is path module used for?

Handling and transforming file system paths across different operating systems.

Q66. What is __dirname and __filename?

Global variables returning the directory name and absolute file name of the current executing module.

Q67. Why are __dirname and __filename not available in ES Modules?

Because ES modules follow standard specifications where these CJS wrappers do not exist natively (handled via import.meta.url).

Q68. What is Event Emitter memory leak warning?

Node warns if more than 10 listeners are attached to a single event emitter instance to prevent leaks.

Q69. How do you increase max event listeners?

Using emitter.setMaxListeners(number).

Q70. What is server-side rendering (SSR)?

Rendering web pages on the server rather than browser client (used in Next.js / Express template engines).

Q71. What is piping in streams?

Connecting a readable stream output directly into a writable stream input using readable.pipe(writable).

Q72. What is backpressure in streams?

A mechanism where a destination stream signals the source stream to slow down data flow when it's overwhelmed.

Q73. What is the difference between PUT and PATCH methods?

PUT replaces the entire resource entity, while PATCH applies partial updates.

Q74. What is RESTful API design?

An architectural style for designing networked APIs using standard HTTP verbs (GET, POST, PUT, DELETE) and stateless operations.

Q75. What is GraphQL?

A query language for APIs allowing clients to request exact data structures they need.

Q76. What are microservices architecture?

Structuring an application as a collection of loosely coupled, independently deployable services.

Q77. What is Docker in Node.js?

Containerization tool used to package Node applications and their exact environment dependencies into portable containers.

Q78. What is CI/CD?

Continuous Integration and Continuous Deployment pipelines automating code testing, building, and production releases.

Q79. How do you secure JWT tokens?

By storing them securely (HttpOnly cookies instead of localStorage), setting short expiry times, and using strong secret signatures.

Q80. What is bcrypt used for?

Hashing passwords securely with salting before saving them to the database.

Q81. What is helmet.js used for?

Setting secure HTTP headers to protect against common web vulnerabilities like XSS and clickjacking.

Q82. What is XSS (Cross-Site Scripting)?

A security vulnerability where attackers inject malicious client scripts into trusted web pages.

Q83. What is SQL Injection?

An attack injecting malicious SQL queries into input fields to manipulate database execution.

Q84. How do you prevent SQL Injection in Node?

By using parameterized queries, prepared statements, or ORMs (Sequelize/Prisma).

Q85. What is worker_threads module?

A built-in module allowing execution of heavy CPU-bound JavaScript tasks in parallel threads without blocking the main event loop.

Q86. What is the difference between cluster and worker_threads?

Cluster spawns independent Node process instances with separate memory, whereas worker_threads share memory space within the same process.

Q87. What is event-driven programming?

A programming paradigm where flow is determined by events such as user actions, messages, or sensor outputs.

Q88. What is uncaughtException event?

A process event emitted when an unhandled synchronous exception bubbles up to the event loop.

Q89. What is unhandledRejection event?

A process event emitted when a Promise is rejected and no catch handler is attached.

Q90. Why should you avoid blocking the event loop?

Because Node.js runs on a single thread for JS execution; blocking it halts all concurrent client requests.

Q91. What is swagger in Node.js?

An open-source toolset for designing, building, documenting, and consuming RESTful APIs.

Q92. What is Winston logger?

A popular multi-transport logging library for Node.js applications.

Q93. What is PM2 ecosystem file?

A configuration file (ecosystem.config.js) used to manage multiple Node applications and instances with PM2.

Q94. What is containerization?

Running applications in isolated user spaces called containers sharing the host OS kernel.

Q95. What is Nginx reverse proxy with Node?

Using Nginx in front of Node.js to handle SSL certificates, load balancing, static file serving, and security masking.

Q96. What is lazy loading in Node.js?

Requiring or importing modules only when they are actually needed rather than at startup.

Q97. What is process.uptime()?

Returns the number of seconds the current Node.js process has been running.

Q98. What is os module used for?

Providing operating system-related utility methods and properties (CPU count, free memory, platform).

Q99. What is assert module?

A built-in module used for writing unit tests to verify invariants and conditions.

Q100. How do you scale a Node.js application?

By implementing horizontal scaling (clustering, PM2, Docker, load balancers) and vertical optimization (caching with Redis, database indexing).