DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Top 50 Node.js Interview Questions with Answers

Top 50 Node.js Interview Questions with Answers

Core Concepts

  1. What is Node.js?
    Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a browser using the V8 engine.

  2. How is Node.js different from JavaScript in the browser?
    Node.js runs on the server-side, can access files and OS, while browser JavaScript is sandboxed.

  3. What is the event loop in Node.js?
    It's a mechanism that handles asynchronous callbacks. It allows Node.js to perform non-blocking I/O operations.

  4. What is the call stack, event queue, and libuv in Node.js?

  • Call stack: Where function execution context is managed
  • Event queue: Holds asynchronous callbacks
  • libuv: C library handling async operations (e.g., file system, DNS)
  1. How does Node.js handle asynchronous operations?
    Through callbacks, promises, async/await and the event loop.

  2. What is the difference between process.nextTick(), setImmediate(), and setTimeout()?

  • process.nextTick(): Executes after current operation, before event loop
  • setImmediate(): Executes after I/O events
  • setTimeout(): Executes after specified delay
  1. Explain the concept of a single-threaded event loop.
    Node.js uses a single thread for handling requests and offloads heavy tasks to background threads.

  2. What are Streams in Node.js? Types?
    Streams are used to read/write data efficiently. Types: Readable, Writable, Duplex, Transform.

  3. How are Buffers different from Streams?
    Buffers hold raw binary data in memory, while streams read/write data chunk by chunk.

  4. How is non-blocking I/O achieved in Node.js?
    Using callbacks, Promises, async/await and libuv for background operations.

Modules & Architecture

  1. What is the CommonJS module system?
    Node.js uses CommonJS to manage modules using require() and module.exports.

  2. How is ES6 module system different?
    Uses import/export, supports static analysis, needs .mjs or "type": "module" in package.json.

  3. What is the difference between require and import?

* `require` is synchronous (CommonJS)
* `import` is asynchronous (ES Modules)
Enter fullscreen mode Exit fullscreen mode
  1. What is the role of the exports object?
    Defines what a module exposes to other modules.

  2. How to create and publish a custom npm package?

* Create `package.json`
* Add module code
* `npm login`
* `npm publish`
Enter fullscreen mode Exit fullscreen mode
  1. What is the package.json file used for?
    It manages project metadata, dependencies, scripts, etc.

  2. What is the difference between dependencies and devDependencies?

* `dependencies`: Needed for production
* `devDependencies`: Only needed during development
Enter fullscreen mode Exit fullscreen mode
  1. What are peerDependencies in npm? Declares compatible versions for a package's dependencies (used in libraries).

File System & Path

  1. How to read/write files using the fs module?

    fs.readFile('file.txt', (err, data) => {});
    fs.writeFile('file.txt', 'Hello', err => {});
    
  2. Difference between fs.readFile and fs.readFileSync?

* `readFile`: async
* `readFileSync`: blocking, sync
Enter fullscreen mode Exit fullscreen mode
  1. How to handle large files in Node.js?
    Use streams: fs.createReadStream() and fs.createWriteStream()

  2. How to use the path module in Node.js?

    const path = require('path');
    path.join(__dirname, 'file.txt');
    

HTTP & Networking

  1. How to create a basic HTTP server in Node.js?

    const http = require('http');
    http.createServer((req, res) => {
      res.end('Hello');
    }).listen(3000);
    
  2. What are request and response objects?

* `req`: contains incoming data
* `res`: used to send back data
Enter fullscreen mode Exit fullscreen mode
  1. How to handle routes in native Node.js?
    Use req.url and req.method to define custom logic

  2. How to handle file uploads?
    Use middleware like multer in Express.

  3. Difference between HTTP and HTTPS in Node.js?
    HTTPS adds SSL/TLS encryption. Use https module and certificates.

Express.js & Frameworks

  1. What is Express.js and why use it?
    Minimalist web framework for routing, middleware, and handling requests easily.

  2. What are middleware functions in Express.js?
    Functions that run between the request and response cycle.

  3. How to handle routes in Express?

    app.get('/route', (req, res) => {});
    
  4. How to implement error handling middleware in Express?

    app.use((err, req, res, next) => {
      res.status(500).send(err.message);
    });
    
  5. What is CORS and how do you handle it in Express?
    Use cors package: app.use(require('cors')());

  6. How to serve static files using Express?
    app.use(express.static('public'));

  7. How to manage cookies and sessions in Express?
    Use cookie-parser and express-session middleware.

Databases & ORMs

  1. How to connect MongoDB with Node.js?
    Use mongoose or mongodb driver.

  2. Difference between Mongoose and native MongoDB driver?
    Mongoose provides schema, validation, and middleware.

  3. How to handle SQL databases with Node.js?
    Use mysql, pg, or ORMs like sequelize, knex.

  4. What are ORMs like Sequelize or TypeORM?
    Abstracts SQL into models and methods for easy interaction.

  5. How to prevent NoSQL injection attacks in Node.js?
    Validate input, avoid dynamic queries, use ORMs safely.

Security & Auth

  1. How to implement authentication in Node.js?
    Use JWT or session-based auth with middleware.

  2. Difference between JWT and session-based auth?

* JWT: token stored on client, stateless
* Session: server stores session ID
Enter fullscreen mode Exit fullscreen mode
  1. What is CSRF and how to prevent it?
    Use tokens (csurf middleware) and validate them.

  2. What are common Node.js security best practices?

* Input validation
* Avoid eval
* Use helmet
* Keep dependencies updated
Enter fullscreen mode Exit fullscreen mode

Advanced & Performance

  1. What is clustering in Node.js?
    Use cluster module to spawn child processes to utilize multiple CPU cores.

  2. How to scale Node.js applications?
    Use clustering, load balancing (Nginx), PM2, and microservices.

  3. What are worker threads?
    Native threads in Node.js for CPU-intensive tasks without blocking the event loop.

  4. How to debug a Node.js application?
    Use Chrome DevTools, node inspect, or console.log.

  5. How to monitor and log Node.js applications?
    Use tools like Winston, Morgan, PM2, and ELK stack.

  6. What are memory leaks and how to avoid them in Node?

* Avoid global variables
* Clean up timers, listeners
* Use memory profiling tools
Enter fullscreen mode Exit fullscreen mode
  1. What tools or libraries do you use for performance optimization?
* PM2
* loadtest / Artillery
* Profiler
* Caching (Redis)
* Compression middleware
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.