Node.js Interview Questions and Answers for Freshers and Experienced (43 Questions)

Quick answer: These 43 Node.js interview questions and answers cover what is asked most in Node.js developer, MERN stack and full-stack developer interviews: Node.js basics, modules and core APIs, asynchronous programming, Express.js, databases, authentication and security, performance and scaling, and testing and real-time apps. Key answers include short code examples.

Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.

Contents

1. Node.js Basics Interview Questions

Q1. What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 engine that lets you run JavaScript outside the browser, mainly on servers. It uses an event-driven, non-blocking I/O model, which makes it efficient for APIs, real-time apps and tools that handle many connections.

Q2. Is Node.js single-threaded?

Your JavaScript runs on a single main thread with an event loop. Slow I/O work such as file and network operations is handed to the operating system or libuv's thread pool, so Node.js can handle many requests at once without creating a thread per request.

Q3. What is the event loop in Node.js?

The event loop keeps checking for completed operations and runs their callbacks. It moves through phases: timers (setTimeout, setInterval), pending callbacks, poll (I/O), check (setImmediate) and close callbacks. Promise callbacks and process.nextTick run between phases.

Q4. What is non-blocking I/O?

Non-blocking I/O means Node.js starts an operation, such as reading a file, and continues with other work instead of waiting. When the operation finishes, its callback or promise is handled by the event loop.

Q5. What is the difference between Node.js and JavaScript in the browser?

Both run JavaScript, but the browser provides the DOM, window and browser APIs, while Node.js provides modules for files, networking, processes and operating system access. Node.js has no DOM.

Q6. When should you not use Node.js?

Node.js is not ideal for long CPU-heavy tasks such as video encoding or large calculations on the main thread, because they block the event loop. Worker threads, child processes or other languages suit those tasks better.

Q7. What is npm?

npm is Node's package manager and public registry. You use it to install libraries (npm install express), manage versions in package.json, and run scripts (npm run dev).

Q8. What is the difference between dependencies and devDependencies?

dependencies are needed to run the application in production, such as express. devDependencies are only needed during development or testing, such as nodemon, jest or eslint.

Q9. What is package-lock.json?

package-lock.json records the exact versions of every installed package and their dependencies, so that installs are identical on every machine. It should be committed to version control.

2. Modules and Core APIs Interview Questions

Q10. What is the difference between CommonJS and ES modules?

CommonJS uses require() and module.exports and loads modules synchronously; it is Node's traditional format. ES modules use import and export, load asynchronously, and are enabled with "type": "module" in package.json or the .mjs extension.

// CommonJS
const fs = require('fs');
module.exports = { add };

// ES module
import fs from 'fs';
export function add(a, b) { return a + b; }

Q11. Name some core modules in Node.js.

fs (file system), path, http and https, os, events, stream, crypto, url, child_process, worker_threads and util.

Q12. What is the EventEmitter?

EventEmitter, from the events module, lets objects emit named events and register listeners for them. Many Node.js objects, such as streams and HTTP servers, are event emitters.

const EventEmitter = require('events');
const bus = new EventEmitter();
bus.on('order', id => console.log('New order', id));
bus.emit('order', 101);

Q13. What are streams in Node.js?

Streams process data piece by piece instead of loading it all into memory. There are readable, writable, duplex and transform streams. They are used for large files, HTTP requests and responses, and compression.

const fs = require('fs');
fs.createReadStream('big.log')
  .pipe(fs.createWriteStream('copy.log'));

Q14. What is a Buffer?

A Buffer holds raw binary data, such as file contents or network packets, outside the normal JavaScript string handling.

Q15. What is the difference between readFile and readFileSync?

readFile is asynchronous and does not block the event loop. readFileSync blocks until the file is read, so it should only be used at startup or in scripts, not inside request handlers.

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

process.nextTick runs its callback immediately after the current operation, before the event loop continues. setImmediate runs its callback in the check phase of the next loop iteration.

Q17. What are environment variables and how do you use them?

Environment variables hold configuration such as ports, database URLs and secrets outside the code. Read them with process.env.PORT. In development they are often loaded from a .env file with the dotenv package, which should not be committed.

3. Asynchronous Programming Interview Questions

Q18. What is callback hell and how do you avoid it?

Callback hell is deeply nested callbacks that are hard to read and handle errors in. Avoid it with promises, async/await, small named functions and libraries that return promises.

Q19. How do async and await work in Node.js?

An async function returns a promise. await pauses that function until the promise settles, without blocking the event loop. Use try/catch for errors.

const fs = require('fs/promises');
async function readConfig() {
  try {
    const data = await fs.readFile('config.json', 'utf8');
    return JSON.parse(data);
  } catch (err) {
    console.error('Cannot read config', err);
  }
}

Q20. How do you run several async tasks in parallel?

Use Promise.all for tasks that must all succeed, or Promise.allSettled to get every result even if some fail.

const [users, orders] = await Promise.all([getUsers(), getOrders()]);

Q21. What is an error-first callback?

In Node's callback style, the first argument of the callback is an error (or null) and the following arguments are the results, as in fs.readFile(path, (err, data) => { … }).

Q22. How do you handle unhandled promise rejections?

Always add catch or try/catch around awaited code. As a safety net, listen to process.on('unhandledRejection'), log the error and shut down gracefully, since recent Node versions exit the process on unhandled rejections.

Preparing for a Node.js interview? We run live one-to-one classes and mock interviews in JavaScript, Node.js and full-stack development, arranged around your free time. Chat on WhatsApp.

4. Express.js Interview Questions

Q23. What is Express.js?

Express is a minimal web framework for Node.js that adds routing, middleware and helpers for building web servers and REST APIs.

Q24. How do you create a simple REST API with Express?

Create an app, add JSON parsing middleware, define routes and start listening on a port.

const express = require('express');
const app = express();
app.use(express.json());

app.get('/api/users/:id', async (req, res) => {
  const user = await db.findUser(req.params.id);
  if (!user) return res.status(404).json({ error: 'Not found' });
  res.json(user);
});

app.post('/api/users', async (req, res) => {
  const user = await db.createUser(req.body);
  res.status(201).json(user);
});

app.listen(process.env.PORT || 3000);

Q25. What is middleware in Express?

Middleware is a function with (req, res, next) that runs during the request–response cycle. It can read or change the request, end the response, or call next() to pass control on. Logging, authentication, body parsing and CORS are common middleware.

Q26. How do you handle errors in Express?

Define an error-handling middleware with four parameters (err, req, res, next) after all routes. In Express 5, errors thrown in async handlers are passed to it automatically; in Express 4 you call next(err) or use a wrapper.

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: 'Something went wrong' });
});

Q27. What is the difference between req.params, req.query and req.body?

req.params holds route parameters such as /users/:id. req.query holds query-string values such as ?page=2. req.body holds the parsed request body, such as JSON sent in a POST request.

Q28. What is CORS and how do you enable it?

CORS is a browser rule that blocks calls to another domain unless the server allows it. In Express, use the cors middleware and list the allowed origins.

Q29. How do you structure a large Express project?

Separate routes, controllers, services (business logic), models or repositories (data access), middleware and configuration into folders, and keep each module focused on one job.

5. Databases, Authentication and Security Interview Questions

Q30. How do you connect Node.js to a database?

Use a driver or ORM: mongoose for MongoDB, pg or Prisma for PostgreSQL, mysql2 or Sequelize for MySQL. Keep connection strings in environment variables and reuse a connection pool.

Q31. What is Mongoose?

Mongoose is an ODM library for MongoDB. It defines schemas and models, validates data, and provides query helpers and middleware.

Q32. How do you implement JWT authentication?

On login, verify the password (hashed with bcrypt), then sign a token with jsonwebtoken. Clients send it in the Authorization header, and a middleware verifies it before protected routes.

const jwt = require('jsonwebtoken');
function auth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Unauthorized' });
  }
}

Q33. How do you store passwords?

Hash them with bcrypt or argon2, which add a salt and are deliberately slow. Never store or log plain-text passwords.

Q34. What are common security practices in Node.js apps?

Validate input, use parameterised queries, set security headers with helmet, enable rate limiting, keep secrets in environment variables, update dependencies and run npm audit, and use HTTPS.

6. Performance and Scaling Interview Questions

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

Run several instances to use all CPU cores, using the cluster module or a process manager such as PM2, place them behind a load balancer, cache with Redis, and scale horizontally with containers.

Q36. What are worker threads?

Worker threads run JavaScript in parallel threads, which suits CPU-heavy tasks such as image processing, so the main event loop stays responsive.

Q37. What is the difference between cluster and worker threads?

The cluster module starts multiple Node.js processes that share a server port, each with its own memory. Worker threads run inside one process and can share memory, which suits CPU-bound tasks rather than handling more HTTP connections.

Q38. How do you find a memory leak in Node.js?

Watch memory over time, take heap snapshots with Chrome DevTools or node –inspect, and compare them. Common causes are growing global arrays or caches, unremoved event listeners and timers that are never cleared.

Q39. What is PM2?

PM2 is a process manager for Node.js that keeps apps running, restarts them after crashes, runs them in cluster mode, and manages logs.

7. Testing and Real-Time Apps Interview Questions

Q40. How do you test a Node.js application?

Use Jest or Mocha with Chai for unit tests, Supertest for testing Express routes, and mocks for external services and databases.

Q41. What are WebSockets and Socket.IO?

WebSockets keep a two-way connection open between client and server for real-time updates such as chat and live dashboards. Socket.IO is a library built on WebSockets that adds rooms, reconnection and fallbacks.

Q42. What is the difference between REST and GraphQL?

REST exposes multiple endpoints, each returning a fixed data shape. GraphQL exposes one endpoint where the client asks for exactly the fields it needs, which reduces over-fetching but adds server complexity.

Q43. What is the MERN stack?

MERN is MongoDB, Express, React and Node.js: a full JavaScript stack for building web applications.

How to Prepare for a Node.js Interview

  1. Master the event loop: explain it with a small code example and the output order.
  2. Be strong in async JavaScript: callbacks, promises and async/await.
  3. Know Express well: routing, middleware order and error handling.
  4. Build and deploy an API: with a database, JWT authentication and validation.
  5. Talk about scaling: cluster, PM2, caching and why CPU-heavy work blocks Node.js.

Next steps: revise JavaScript interview questions and SQL interview questions, and see all subjects on our interview questions page.

Want a mentor for your preparation? We teach JavaScript, Node.js and full-stack development through live online classes arranged around your free time, with mock interviews before your placement. Message us on WhatsApp or email engineersrworld@gmail.com.

More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.

Frequently Asked Questions

Which Node.js topics are asked most in interviews?

The event loop, non-blocking I/O, callbacks versus promises versus async/await, Express middleware, streams, error handling and JWT authentication come up in most Node.js interviews.

Should I learn JavaScript fully before Node.js?

Yes. Closures, promises, async/await and modules are core JavaScript topics, and Node.js interviews assume you know them well.

Is Node.js good for freshers in India?

Yes. Node.js with React (MERN) is popular in start-ups and product companies, and many full-stack fresher roles ask for it.

How should I prepare for a Node.js interview?

Build a REST API with Express, MongoDB or PostgreSQL, JWT authentication, validation and error handling, deploy it, and be ready to explain the event loop with a code example.

Scroll to Top