DEV Community

vivek
vivek

Posted on

Node JS top 20 questions

Here’s a list of 20 Node.js interview questions, covering both basic and advanced topics for a comprehensive preparation:


Basic Questions

  1. What is Node.js, and why is it used?

    • Node.js is a server-side runtime environment based on the V8 JavaScript engine, used for building fast and scalable network applications.
  2. Explain the event loop in Node.js.

    • The event loop is the mechanism that handles asynchronous callbacks in a single thread by delegating tasks to the system and processing them as events return.
  3. What are streams in Node.js?

    • Streams are objects used for reading or writing continuous chunks of data. Types include:
      • Readable (e.g., file read streams)
      • Writable (e.g., file write streams)
      • Duplex (e.g., sockets)
      • Transform (e.g., zlib for compression).
  4. What is the difference between setImmediate() and process.nextTick()?

    • setImmediate(): Executes after the current event loop completes.
    • process.nextTick(): Executes before the next event loop iteration begins.
  5. How does Node.js handle concurrency?

    • Node.js uses an event-driven, non-blocking I/O model via the event loop. Heavy computations are offloaded to worker threads or background processes.
  6. How do you handle uncaught exceptions in Node.js?

    • Use the process.on('uncaughtException', callback) event to handle uncaught exceptions, but it's recommended to exit the process after logging the error.

Intermediate Questions

  1. What is middleware in Node.js? Provide an example.
    • Middleware functions in frameworks like Express.js process requests and responses.
   const express = require('express');
   const app = express();

   app.use((req, res, next) => {
     console.log('Middleware executed');
     next(); // Passes control to the next middleware/route handler
   });

   app.get('/', (req, res) => res.send('Hello World'));
   app.listen(3000);
Enter fullscreen mode Exit fullscreen mode
  1. How do you manage environment variables in Node.js?
    • Use the dotenv package to load environment variables from a .env file:
   require('dotenv').config();
   console.log(process.env.MY_VARIABLE);
Enter fullscreen mode Exit fullscreen mode
  1. What are worker threads in Node.js?
    • Worker threads are used to execute CPU-intensive JavaScript code in parallel, enabling better performance for heavy computations:
   const { Worker } = require('worker_threads');
   const worker = new Worker('./worker.js');
Enter fullscreen mode Exit fullscreen mode
  1. Explain the cluster module in Node.js.

    • The cluster module allows Node.js to spawn multiple processes (workers) sharing the same server port to leverage multi-core CPUs:
    const cluster = require('cluster');
    const http = require('http');
    if (cluster.isMaster) {
      cluster.fork(); // Create worker processes
    } else {
      http.createServer((req, res) => res.end('Hello')).listen(8000);
    }
    
  2. What is the difference between blocking and non-blocking I/O?

    • Blocking I/O: Operations that block the event loop until completion (e.g., fs.readFileSync).
    • Non-blocking I/O: Operations that allow the event loop to continue while waiting for execution (e.g., fs.readFile).
  3. What is the libuv library in Node.js?

    • libuv is a C library used by Node.js to handle the event loop, asynchronous I/O, and thread pool.

Advanced Questions

  1. What are the differences between spawn(), fork(), and exec() in the child_process module?

    • spawn(): Executes a command and streams the output.
    • fork(): Spawns a new Node.js process for IPC (Inter-Process Communication).
    • exec(): Executes a command and buffers the output.
  2. What is the purpose of the cluster module in scaling Node.js applications?

    • The cluster module enables horizontal scaling by creating worker processes to handle concurrent requests using multi-core CPUs.
  3. What is the difference between req.params, req.query, and req.body in Express.js?

    • req.params: Retrieves route parameters (e.g., /users/:id).
    • req.query: Retrieves query string parameters (e.g., /users?id=123).
    • req.body: Retrieves payload data from POST/PUT requests.
  4. How do you secure a Node.js application?

    • Use HTTPS.
    • Validate and sanitize inputs to prevent SQL injection and XSS.
    • Implement rate limiting to prevent brute force attacks.
    • Use libraries like helmet for HTTP header security.
  5. What are memory leaks in Node.js, and how can you debug them?

    • Memory leaks occur when objects are no longer needed but not garbage-collected. Tools like node --inspect, Chrome DevTools, or heapdump can help identify leaks.
  6. What is event emitter, and how is it used in Node.js?

    • The EventEmitter class allows objects to subscribe to and emit events:
    const EventEmitter = require('events');
    const emitter = new EventEmitter();
    
    emitter.on('event', () => console.log('Event triggered'));
    emitter.emit('event');
    
  7. How does Node.js handle large file uploads efficiently?

    • By using streams, Node.js processes chunks of data rather than loading the entire file into memory:
    const fs = require('fs');
    const server = require('http').createServer((req, res) => {
      req.pipe(fs.createWriteStream('file.txt'));
      res.end('Upload complete');
    }).listen(3000);
    
  8. Explain the role of package-lock.json and why it is important.

    • package-lock.json locks dependency versions to ensure consistent installs across environments, improving reproducibility and avoiding unexpected issues.

Bonus Topics

  • Explain how you would implement WebSockets in Node.js.
  • Discuss the advantages and challenges of serverless with Node.js.
  • Implement a custom middleware in Express.js.

Top comments (0)