Node.js Interview Questions

68 questions with detailed answers

Question:
What is the V8 engine and how does Node.js use it?
Answer:
V8 is Google's open-source JavaScript engine written in C++. Node.js uses V8 to: 1) Compile JavaScript to native machine code, 2) Execute JavaScript outside the browser, 3) Provide memory management and garbage collection, 4) Offer high performance JavaScript execution.

Question:
Explain the concept of non-blocking I/O in Node.js.
Answer:
Non-blocking I/O means operations don't wait for completion before moving to the next task. In Node.js: 1) I/O operations are asynchronous, 2) Callbacks/promises handle completion, 3) Event loop manages execution, 4) Prevents thread blocking, 5) Enables high concurrency with single thread.

Question:
What is npm and what is its purpose?
Answer:
NPM (Node Package Manager) is the default package manager for Node.js. Purpose: 1) Install and manage packages, 2) Handle dependencies, 3) Version management, 4) Script execution, 5) Package publishing, 6) Largest software registry in the world.

Question:
How do you create a simple HTTP server in Node.js?
Answer:
```javascript const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }); server.listen(3000, () => { console.log('Server running on port 3000'); }); ```

Question:
What is the difference between require() and import in Node.js?
Answer:
require() is CommonJS syntax (synchronous), import is ES6 modules (asynchronous). require() can be called conditionally, import must be at top level. require() returns object directly, import uses destructuring. Node.js supports both with proper configuration.

Question:
What are modules in Node.js? Explain built-in, local, and third-party modules.
Answer:
Modules are reusable blocks of code. Built-in: fs, http, path (core modules). Local: custom files using module.exports. Third-party: installed via npm. Each module has its own scope, preventing global pollution.

Question:
What is package.json and what information does it contain?
Answer:
package.json is project metadata file containing: name, version, description, main entry point, scripts, dependencies, devDependencies, author, license, repository info. Essential for npm package management.

Question:
How do you handle errors in Node.js?
Answer:
Error handling methods: 1) try-catch for synchronous code, 2) Error-first callbacks, 3) Promise .catch(), 4) async/await with try-catch, 5) process.on("uncaughtException"), 6) EventEmitter error events.

Question:
What is the purpose of process.env in Node.js?
Answer:
process.env provides access to environment variables. Used for: configuration settings, API keys, database URLs, port numbers, environment-specific values. Keeps sensitive data out of source code.

Question:
Explain the difference between console.log() and process.stdout.write().
Answer:
console.log() adds newline automatically, process.stdout.write() doesn't. console.log() accepts multiple arguments, stdout.write() accepts only strings/buffers. console.log() is higher-level, stdout.write() is lower-level.

Question:
What is the global object in Node.js?
Answer:
Global object in Node.js is "global" (not window like browsers). Contains: process, Buffer, console, setTimeout, setInterval, clearTimeout, clearInterval. Variables declared without var/let/const become global properties.

Question:
How do you read command line arguments in Node.js?
Answer:
Use `process.argv` array. First two elements are node path and script path. Actual arguments start from index 2. Example: `process.argv[2]` for first argument. Libraries like `yargs` provide better parsing.

Question:
What is the purpose of __dirname and __filename in Node.js?
Answer:
__dirname: absolute path of directory containing current file. __filename: absolute path of current file. Useful for file operations, requiring modules with relative paths, building file paths dynamically.

Question:
How do you create and export a module in Node.js?
Answer:
`module.exports = value;` or `exports.property = value;` Example: ```javascript module.exports = {func1, func2}; // or exports.myFunction = () => {}; ``` Import with `require("./module")`. ES6: `export default` or `export {}`.

Question:
What is the purpose of package.json and package-lock.json?
Answer:
package.json contains project metadata and dependencies. package-lock.json locks specific versions of dependencies and their sub-dependencies, ensuring consistent installations across environments and improving security.

Question:
How do you handle environment variables in Node.js?
Answer:
Use process.env to access variables, dotenv package to load from .env files, validate required variables at startup, use different files for different environments, and never commit sensitive data to version control.

Question:
What is Node.js and what makes it different from other server-side technologies?
Answer:
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows JavaScript to run on the server-side. Key differences: 1) Single-threaded with event loop, 2) Non-blocking I/O operations, 3) Uses JavaScript for both client and server, 4) NPM package ecosystem, 5) High performance for I/O intensive applications.

Question:
Explain the Event Loop in Node.js and how it works.
Answer:
The Event Loop is Node.js's mechanism for handling asynchronous operations. Phases: 1) Timer phase (setTimeout, setInterval), 2) Pending callbacks, 3) Idle/prepare, 4) Poll phase (fetch new I/O events), 5) Check phase (setImmediate), 6) Close callbacks. It continuously cycles through these phases.

Question:
What are callbacks and what is callback hell? How can you avoid it?
Answer:
Callbacks are functions passed as arguments to other functions. Callback hell is nested callbacks creating pyramid-like code structure. Solutions: 1) Use Promises, 2) Async/await, 3) Modularize code, 4) Use libraries like async.js, 5) Error-first callback pattern.

Question:
What are Promises and how do they help in handling asynchronous operations?
Answer:
Promises represent eventual completion/failure of asynchronous operations. Benefits: 1) Better error handling with .catch(), 2) Chaining with .then(), 3) Avoid callback hell, 4) States: pending, fulfilled, rejected, 5) Promise.all() for parallel execution, 6) More readable code.

Question:
What are Streams in Node.js? Explain different types of streams.
Answer:
Streams are objects for reading/writing data in chunks. Types: 1) Readable (fs.createReadStream), 2) Writable (fs.createWriteStream), 3) Duplex (TCP sockets), 4) Transform (zlib.createGzip). Benefits: Memory efficient, time efficient, composable through piping.

Question:
What is middleware in Express.js and how does it work?
Answer:
Middleware functions execute during request-response cycle. They have access to req, res, and next(). Types: 1) Application-level, 2) Router-level, 3) Error-handling, 4) Built-in, 5) Third-party. Execute in order defined, can modify req/res objects, must call next() to continue.

Question:
Explain async/await and how it improves code readability.
Answer:
async/await is syntactic sugar over Promises. async function returns Promise, await pauses execution until Promise resolves. Benefits: synchronous-looking code, better error handling with try-catch, no callback hell, easier debugging.

Question:
Explain the concept of clustering in Node.js.
Answer:
Clustering creates multiple worker processes sharing same port. Master process manages workers, distributes load. Benefits: utilize multiple CPU cores, improve performance, fault tolerance. Use cluster module or PM2 for production.

Question:
What is the difference between spawn(), exec(), and fork() in child processes?
Answer:
spawn(): streams data, good for large output. exec(): buffers output, good for small output. fork(): special spawn for Node.js files, enables IPC. spawn() most memory efficient, exec() simplest for shell commands.

Question:
How do you handle memory leaks in Node.js applications?
Answer:
Prevention: avoid global variables, clear timers/intervals, remove event listeners, close streams/connections. Detection: use --inspect flag, heap snapshots, tools like clinic.js, monitor memory usage patterns.

Question:
What is the purpose of Buffer in Node.js?
Answer:
Buffer handles binary data before Uint8Array was available. Used for: file operations, network protocols, cryptography. Methods: Buffer.from(), Buffer.alloc(), toString(). Now Uint8Array is preferred for new code.

Question:
Explain the difference between readFile() and createReadStream().
Answer:
readFile(): loads entire file into memory, callback-based, good for small files. createReadStream(): reads in chunks, stream-based, memory efficient for large files, supports backpressure, pipe-able.

Question:
What are EventEmitters and how do you use them?
Answer:
EventEmitters implement observer pattern. Methods: on()/addListener(), emit(), once(), removeListener(). Used throughout Node.js core. Custom: extend EventEmitter class, emit custom events, handle asynchronously.

Question:
How do you implement authentication and authorization in Node.js?
Answer:
Authentication: verify identity (JWT, sessions, OAuth). Authorization: verify permissions (role-based, ACL). Tools: passport.js, jsonwebtoken, express-session. Store tokens securely, validate on each request.

Question:
What is CORS and how do you handle it in Node.js?
Answer:
CORS (Cross-Origin Resource Sharing) allows/restricts cross-domain requests. Handle with: cors middleware, manual headers (Access-Control-Allow-Origin), preflight requests for complex requests. Configure origins, methods, headers.

Question:
Explain the concept of worker threads in Node.js.
Answer:
Worker threads enable parallel JavaScript execution for CPU-intensive tasks. Use worker_threads module. Main thread communicates via message passing. Benefits: true parallelism, don't block event loop, shared memory with SharedArrayBuffer.

Question:
Explain the Event Loop in Node.js and how it handles asynchronous operations.
Answer:
The Event Loop is the core mechanism that allows Node.js to perform non-blocking I/O operations. It continuously checks the call stack and callback queue, executing callbacks when the call stack is empty. It has multiple phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks.

Question:
What are the differences between require() and import statements in Node.js?
Answer:
require() is part of CommonJS module system, synchronous, and can be called conditionally. import is part of ES6 modules, asynchronous, must be at top level, and provides better tree-shaking and static analysis.

Question:
Explain the concept of middleware in Express.js with examples.
Answer:
Middleware functions execute during the request-response cycle. They have access to req, res, and next objects. Examples include authentication middleware, logging middleware, and error handling middleware. They can modify request/response objects or terminate the cycle.

Question:
How do you handle errors in Node.js applications?
Answer:
Error handling in Node.js can be done through try-catch blocks for synchronous code, error-first callbacks for asynchronous operations, Promise.catch() for promises, and process.on("uncaughtException") for unhandled errors.

Question:
How do you implement authentication and authorization in a Node.js application?
Answer:
Authentication can be implemented using JWT tokens, sessions, or OAuth. Authorization involves checking user permissions using middleware. Common patterns include role-based access control (RBAC) and attribute-based access control (ABAC).

Question:
What are the best practices for securing a Node.js application?
Answer:
Use HTTPS, validate input, sanitize data, implement rate limiting, use helmet.js for security headers, keep dependencies updated, use environment variables for secrets, implement proper authentication, and use CSRF protection.

Question:
Explain the concept of callback hell and how to avoid it.
Answer:
Callback hell occurs when multiple nested callbacks make code hard to read and maintain. Avoid it by using Promises, async/await, modularizing code into named functions, and using control flow libraries like async.js.

Question:
How do you handle file uploads in Node.js?
Answer:
Use middleware like multer for Express.js to handle multipart/form-data. Configure storage options (memory or disk), set file size limits, validate file types, and implement proper error handling for upload failures.

Question:
What are the different ways to create a server in Node.js?
Answer:
Use http.createServer() for basic HTTP server, https.createServer() for HTTPS, Express.js for web applications, Koa.js for modern async/await support, or Fastify for high performance. Each has different features and use cases.

Question:
How do you implement caching in Node.js applications?
Answer:
Implement in-memory caching with objects/Map, use Redis for distributed caching, implement HTTP caching with headers, use CDN for static assets, and implement application-level caching for database queries and API responses.

Question:
What are the different testing frameworks available for Node.js?
Answer:
Popular frameworks include Jest (feature-rich), Mocha (flexible), Jasmine (behavior-driven), AVA (concurrent), and Tape (minimal). Choose based on features needed like mocking, assertions, coverage, and async testing support.

Question:
What are the best practices for logging in Node.js applications?
Answer:
Use structured logging with libraries like Winston or Bunyan, implement different log levels, avoid logging sensitive data, use correlation IDs for request tracking, implement log rotation, and centralize logs in production.

Question:
How does Node.js handle concurrency despite being single-threaded?
Answer:
Node.js uses: 1) Event-driven architecture, 2) Non-blocking I/O with libuv, 3) Thread pool for file operations, 4) Event loop for coordination, 5) Callbacks/promises for async handling. CPU-intensive tasks can block, but I/O operations are delegated to system.

Question:
Explain the internal architecture of Node.js and libuv.
Answer:
Architecture: 1) V8 Engine (JavaScript execution), 2) libuv (C++ library for async I/O), 3) Node.js bindings, 4) Node.js standard library. Libuv provides: Event loop, thread pool, async I/O operations, file system operations, networking, timers.

Question:
What are the different phases of the Event Loop?
Answer:
1) Timers: setTimeout/setInterval callbacks, 2) Pending callbacks: I/O callbacks deferred, 3) Idle/prepare: internal use, 4) Poll: fetch new I/O events, execute I/O callbacks, 5) Check: setImmediate callbacks, 6) Close callbacks: socket.on('close'). Each phase has a FIFO queue.

Question:
How do you optimize Node.js application performance?
Answer:
1) Use clustering/worker threads, 2) Implement caching (Redis), 3) Database optimization, 4) Use CDN for static assets, 5) Gzip compression, 6) Connection pooling, 7) Avoid blocking operations, 8) Profile with tools like clinic.js, 9) Use streams for large data.

Question:
How do you implement graceful shutdown in Node.js applications?
Answer:
```javascript process.on('SIGTERM', () => { server.close(() => { database.close(); process.exit(0); }); }); ``` Steps: 1) Listen for signals, 2) Stop accepting new requests, 3) Finish existing requests, 4) Close database connections, 5) Clean up resources, 6) Exit process.

Question:
Explain memory management and garbage collection in Node.js.
Answer:
V8 uses generational garbage collection: young generation (Scavenge) and old generation (Mark-Sweep-Compact). Memory spaces: new space, old space, large object space, code space. Optimize by avoiding memory leaks, using object pools.

Question:
What are the security best practices for Node.js applications?
Answer:
1) Validate input, 2) Use HTTPS, 3) Secure headers (helmet.js), 4) Rate limiting, 5) SQL injection prevention, 6) XSS protection, 7) Update dependencies, 8) Environment variables for secrets, 9) Principle of least privilege.

Question:
How do you implement real-time communication using WebSockets?
Answer:
Use Socket.io or ws library. Server: create WebSocket server, handle connections/messages. Client: establish connection, send/receive messages. Features: rooms, namespaces, broadcasting, fallback to polling, authentication.

Question:
Explain the concept of microservices architecture with Node.js.
Answer:
Microservices: small, independent services communicating via APIs. Benefits: scalability, technology diversity, fault isolation. Implementation: Express.js services, API Gateway, service discovery, message queues, containerization (Docker).

Question:
How do you handle database connections and connection pooling?
Answer:
Connection pooling reuses database connections. Configure: pool size, timeout, idle timeout. Libraries: mysql2, pg (PostgreSQL), mongoose (MongoDB). Benefits: reduced connection overhead, better performance, resource management.

Question:
What are the differences between PM2, Forever, and Nodemon?
Answer:
PM2: production process manager, clustering, monitoring, log management. Forever: simple daemon, keeps app running, basic restart. Nodemon: development tool, auto-restart on file changes. PM2 for production, Nodemon for development.

Question:
How do you implement caching strategies in Node.js?
Answer:
Strategies: 1) In-memory (node-cache), 2) Redis, 3) Memcached, 4) HTTP caching headers, 5) CDN. Patterns: cache-aside, write-through, write-behind. Consider TTL, cache invalidation, cache warming, distributed caching.

Question:
Explain the concept of load balancing in Node.js applications.
Answer:
Distribute requests across multiple instances. Types: round-robin, least connections, IP hash. Tools: nginx, HAProxy, AWS ALB. Node.js cluster module for single machine. Consider session affinity, health checks, failover.

Question:
How do you handle large file uploads efficiently?
Answer:
Use streams: multer with diskStorage, busboy for parsing. Techniques: chunked upload, progress tracking, file validation, temporary storage, cleanup on failure. Consider memory usage, disk space, security, virus scanning.

Question:
What are the best practices for error handling and logging in production?
Answer:
Error handling: centralized error middleware, proper HTTP status codes, graceful degradation. Logging: structured logs (JSON), log levels, correlation IDs, avoid sensitive data. Tools: winston, bunyan, ELK stack, monitoring alerts.

Question:
Explain the concept of streams in Node.js and their types.
Answer:
Streams are objects that handle reading/writing data in chunks. Types include Readable (read data), Writable (write data), Duplex (both read/write), and Transform (modify data while reading/writing). They are memory efficient for large data.

Question:
What is clustering in Node.js and when would you use it?
Answer:
Clustering allows creating child processes that share the same server port, enabling utilization of multi-core systems. Use it to improve performance and handle more concurrent connections by distributing load across CPU cores.

Question:
Explain the difference between Buffer and String in Node.js.
Answer:
Buffer handles binary data and has fixed size, while String handles text data with variable size. Buffer is more efficient for binary operations, file I/O, and network operations. Strings are encoded in UTF-8 by default.

Question:
How do you optimize the performance of a Node.js application?
Answer:
Use clustering, implement caching, optimize database queries, use compression, minimize middleware, implement connection pooling, use CDN for static assets, profile and monitor performance, and use async/await properly.

Question:
How do you implement real-time communication in Node.js?
Answer:
Use WebSockets with libraries like Socket.io for bidirectional communication, Server-Sent Events (SSE) for server-to-client communication, or WebRTC for peer-to-peer communication. Choose based on requirements and browser support.

Question:
Explain the concept of microservices architecture in Node.js.
Answer:
Microservices break applications into small, independent services that communicate via APIs. Benefits include scalability, technology diversity, and fault isolation. Challenges include complexity, network latency, and data consistency.

Question:
What is the difference between spawn(), exec(), and fork() in child_process?
Answer:
spawn() launches commands and streams data, exec() runs commands and buffers output, fork() creates new Node.js processes with IPC. Use spawn() for large data, exec() for small output, and fork() for CPU-intensive tasks.

Question:
Explain the concept of database connection pooling in Node.js.
Answer:
Connection pooling reuses database connections to improve performance and resource utilization. It maintains a pool of connections, handles connection lifecycle, prevents connection exhaustion, and reduces connection overhead.

Question:
Explain the concept of graceful shutdown in Node.js applications.
Answer:
Graceful shutdown involves handling SIGTERM/SIGINT signals, closing server connections, finishing ongoing requests, closing database connections, and cleaning up resources before process termination to prevent data loss.
Study Tips
  • Read each question carefully
  • Try to answer before viewing the solution
  • Practice explaining concepts out loud
  • Review regularly to reinforce learning
Share & Practice

Found this helpful? Share with others!

Feedback