Sitemap
Deepaksingh

Deepaksingh

Node.js & Express.js Interview Guide

13 min readSep 9, 2026

--

SECTION 1: Node.js Basics

Q1. What is Node.js?

Node.js is a runtime environment that lets you run JavaScript outside the browser, built on Google Chrome’s V8 JavaScript engine. It’s single-threaded, event-driven, and uses non-blocking I/O, which makes it lightweight and efficient for data-intensive, real-time applications.

Q2. Is Node.js single-threaded or multi-threaded?

Node.js runs your JavaScript code on a single thread (the main/event loop thread). However, internally it uses a thread pool (via libuv) for expensive operations like file I/O, DNS lookups, and crypto — so it's not purely single-threaded at the system level, just single-threaded for your JS execution.

Q3. What makes Node.js fast?

  • Built on V8 engine (compiles JS to machine code)
  • Non-blocking, asynchronous I/O model
  • Event loop handles concurrency without creating new threads per request
  • Efficient for I/O-bound tasks (not CPU-bound tasks)

Q4. What is the difference between synchronous and asynchronous programming in Node.js?

  • Synchronous: Code executes line by line; each operation blocks the next until it finishes.
  • Asynchronous: Operations (like file reads, DB calls) are non-blocking — the code continues executing while the operation completes in the background, and a callback/promise handles the result later.
// Synchronous
const data = fs.readFileSync('file.txt');
console.log(data);
// Asynchronous
fs.readFile('file.txt', (err, data) => {
console.log(data);
});
console.log("This runs first!");

Q5. What is npm?

npm (Node Package Manager) is the default package manager for Node.js. It’s used to install, share, and manage dependencies/libraries, and it maintains a package.json file listing project dependencies and scripts.

Q6. What is package.json vs package-lock.json?

  • package.json: Describes the project — name, version, dependencies, scripts, entry point.
  • package-lock.json: Locks the exact version of every installed package (including sub-dependencies) to ensure consistent installs across machines.

Q7. What are the core/built-in modules in Node.js?

Examples: fs (file system), http/https, path, os, events, stream, crypto, util, url, querystring, child_process, cluster, buffer, zlib.

Q8. Difference between require() and import?

require (CommonJS)import (ES Modules)Synchronous loadingCan be async (dynamic import)Works by default in .js filesNeeds "type": "module" in package.json or .mjs extensionmodule.exports to exportexport/export defaultCan be called conditionallyStatic, hoisted to top

Q9. What is the difference between module.exports and exports?

exports is just a reference to module.exports. If you reassign exports = {}, it breaks the link to module.exports, so nothing gets exported. Safer approach: always use module.exports for full reassignment.

Q10. What is REPL in Node.js?

REPL = Read, Eval, Print, Loop. It’s an interactive shell (accessed by typing node in terminal) that reads JS commands, evaluates them, prints the result, and loops back for more input — useful for quick testing.

SECTION 2: Event Loop & Asynchronous Node.js

Q11. What is the Event Loop?

The event loop is the mechanism that allows Node.js to perform non-blocking I/O despite being single-threaded. It continuously checks the call stack and callback/task queues, executing queued callbacks once the stack is empty.

Q12. Explain the phases of the Event Loop.

  1. Timers — executes setTimeout / setInterval callbacks
  2. Pending callbacks — executes I/O callbacks deferred from previous cycle
  3. Idle, prepare — internal use
  4. Poll — retrieves new I/O events, executes I/O callbacks
  5. Check — executes setImmediate() callbacks
  6. Close callbacks — e.g., socket.on('close')

Between each phase, Node processes the microtask queue (Promises, process.nextTick).

Q13. Difference between process.nextTick(), Promises (microtasks), setTimeout(), and setImmediate()?

  • process.nextTick() — runs before any other microtask, immediately after the current operation, before the event loop continues.
  • Promise callbacks (.then) — run after nextTick queue is empty, still before the event loop moves to the next phase.
  • setTimeout(fn, 0) — runs in the timers phase, after at least the specified delay.
  • setImmediate() — runs in the check phase, after I/O events in the current loop iteration.

Order example:

console.log('start');
setTimeout(() => console.log('setTimeout'), 0);
setImmediate(() => console.log('setImmediate'));
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));
console.log('end');
// Output:
// start
// end
// nextTick
// promise
// setTimeout (or setImmediate — order can vary if not inside I/O)
// setImmediate (or setTimeout)

Q14. What are Callbacks? What is “Callback Hell”?

A callback is a function passed as an argument to be executed after an operation completes. Callback Hell refers to deeply nested callbacks that make code hard to read/maintain:

getUser(id, (user) => {
getPosts(user, (posts) => {
getComments(posts, (comments) => {
// deeply nested - hard to manage
});
});
});

Solved using Promises or async/await.

Q15. What are Promises?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. States: pending, fulfilled, rejected.

const promise = new Promise((resolve, reject) => {
if (success) resolve(data);
else reject(error);
});
promise.then(data => console.log(data)).catch(err => console.error(err));

Q16. What is async/await?

Syntactic sugar over Promises that lets asynchronous code be written in a synchronous-looking style.

async function getUser() {
try {
const res = await fetch('/api/user');
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}

Q17. What is Promise.all(), Promise.race(), Promise.allSettled(), Promise.any()?

  • all() — resolves when all promises resolve; rejects if any one rejects.
  • race() — resolves/rejects as soon as the first promise settles.
  • allSettled() — waits for all to settle (resolved or rejected), returns status of each.
  • any() — resolves as soon as any one promise fulfills; rejects only if all reject.

Q18. What is the difference between blocking and non-blocking code?

Blocking code halts further execution until the current operation finishes (e.g., fs.readFileSync). Non-blocking code allows the program to continue while the operation completes in background (e.g., fs.readFile).

SECTION 3: Streams, Buffers, Events

Q19. What are Streams in Node.js?

Streams are objects used to read/write data continuously in chunks, rather than loading everything into memory at once. Useful for large files, video processing, network communications.

Get Deepaksingh’s stories in your inbox

Join Medium for free to get updates from this writer.

Types of streams:

  • Readable (e.g., fs.createReadStream)
  • Writable (e.g., fs.createWriteStream)
  • Duplex (both readable & writable, e.g., TCP sockets)
  • Transform (modify data while reading/writing, e.g., zlib.createGzip)

Q20. What is a Buffer in Node.js?

A Buffer is a temporary storage for raw binary data (outside the V8 heap), used when dealing with streams, files, or network operations where data isn’t in string/JS-object form.

const buf = Buffer.from('Hello');
console.log(buf); // <Buffer 48 65 6c 6c 6f>

Q21. What is the EventEmitter class?

EventEmitter (from the events module) allows objects to emit named events and register listener functions ("subscribers") for those events — core to Node's event-driven architecture.

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => console.log(`Hello, ${name}`));
emitter.emit('greet', 'John');

Q22. How does Node.js handle file uploads/large data without running out of memory?

By using streams — reading/writing data in small chunks (buffers) instead of loading the entire file into memory, then piping data from a readable stream to a writable stream.

fs.createReadStream('input.txt').pipe(fs.createWriteStream('output.txt'));

SECTION 4: Node.js Deeper Concepts

Q23. What is the difference between process.nextTick() and setImmediate() (deep dive)?

process.nextTick() callbacks run before the event loop continues to the next phase — even before Promise microtasks. setImmediate() runs in the check phase, which comes after I/O callbacks. Overusing nextTick can starve the event loop (I/O never gets a chance to run) since it keeps adding to the front of the queue.

Q24. What is Clustering in Node.js? Why is it needed?

Since Node.js runs on a single thread, it can’t use multiple CPU cores by default. The cluster module allows spawning multiple child processes (workers), each with its own event loop, that share the same server port — enabling horizontal scaling across CPU cores.

const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
} else {
require('./server');
}

Q25. Difference between cluster and worker_threads?

  • cluster: Creates multiple independent processes (separate memory), good for scaling network/HTTP servers.
  • worker_threads: Creates threads within the same process that can share memory (via SharedArrayBuffer), better for CPU-intensive tasks like image processing or heavy computation.

Q26. How does Node.js handle CPU-intensive tasks if it’s single-threaded?

Since CPU-bound tasks block the event loop, Node handles them via:

  • worker_threads (parallel JS execution)
  • child_process (spawn separate processes)
  • Offloading to external services/queues (e.g., message queues, background job processors)

Q27. What is middleware in the context of Node.js (general concept, not just Express)?

Middleware is code that runs between receiving a request and sending a response — used to process, modify, validate, or log requests/responses. (Express formalizes this concept extensively — see Section 6.)

Q28. What are child processes in Node.js?

Child processes allow Node to execute external commands/programs or run other Node scripts in parallel, useful for CPU-heavy tasks. Methods: spawn(), exec(), execFile(), fork().

  • spawn() — streams data, good for large output
  • exec() — buffers output, good for small output, uses shell
  • fork() — special case of spawn for running Node.js modules, creates IPC channel

Q29. What is libuv?

libuv is a C library that Node.js uses to implement the event loop, asynchronous I/O, and thread pool. It abstracts away platform-specific async I/O differences (Linux, Windows, macOS).

Q30. What is the difference between setTimeout and setInterval?

  • setTimeout(fn, delay) — executes fn once after delay ms.
  • setInterval(fn, delay) — executes fn repeatedly every delay ms until cleared with clearInterval().

Q31. How do you handle uncaught exceptions and unhandled promise rejections in Node.js?

process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1); // recommended: exit after cleanup
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
});

Best practice: don’t rely on these for control flow — use proper try/catch and .catch() throughout your code; these are last-resort safety nets.

Q32. What is memory leak in Node.js and how do you detect it?

A memory leak occurs when memory that’s no longer needed isn’t released (e.g., global variables holding references, uncleared timers/listeners, closures holding large data). Detected using tools like Chrome DevTools, --inspect flag, heapdump, or clinic.js.

Q33. What is the difference between __dirname and __filename?

  • __dirname — absolute path of the directory containing the current file.
  • __filename — absolute path of the current file itself (including filename).

Q34. What is the purpose of the path module?

Provides utilities for working with file and directory paths in a cross-platform way (path.join, path.resolve, path.basename, path.extname, etc.), avoiding manual string concatenation issues between OS (Windows \ vs Unix /).

Q35. What is the difference between fs.readFile and fs.createReadStream?

  • fs.readFile — reads the entire file into memory at once, then calls back — bad for large files.
  • fs.createReadStream — reads file in chunks, memory-efficient for large files, ideal for streaming.

SECTION 5: Express.js Basics

Q36. What is Express.js?

Express is a minimal, flexible Node.js web application framework that provides a robust set of features for building web applications and APIs — routing, middleware support, template engine integration, etc. It simplifies working with the raw http module.

Q37. How do you create a basic Express server?

const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => console.log('Server running on port 3000'));

Q38. What is Middleware in Express?

Middleware functions are functions that have access to the request object (req), response object (res), and the next() function in the request-response cycle. They can execute code, modify req/res, end the cycle, or call next() to pass control to the next middleware.

app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});

Q39. What are the types of Middleware in Express?

  1. Application-level middleware — bound using app.use() or app.METHOD()
  2. Router-level middleware — bound to an instance of express.Router()
  3. Error-handling middleware — has 4 arguments (err, req, res, next)
  4. Built-in middleware — e.g., express.json(), express.static()
  5. Third-party middleware — e.g., cors, morgan, helmet

Q40. How does routing work in Express?

Routing defines how an application responds to client requests at specific endpoints (URI + HTTP method).

app.get('/users', (req, res) => { /* get all users */ });
app.post('/users', (req, res) => { /* create user */ });
app.put('/users/:id', (req, res) => { /* update user */ });
app.delete('/users/:id', (req, res) => { /* delete user */ });

Q41. What is express.Router()?

It’s a mini Express application used to create modular, mountable route handlers — helps organize routes into separate files.

// userRoutes.js
const router = require('express').Router();
router.get('/', (req, res) => res.send('All users'));
module.exports = router;
// app.js
app.use('/users', require('./userRoutes'));

Q42. Difference between app.use() and app.get()/post()?

  • app.use() — matches all HTTP methods and can match partial paths (mounts middleware).
  • app.get()/post()/etc. — matches a specific HTTP method and exact route path.

Q43. What is req.params, req.query, and req.body?

  • req.params — route parameters (/users/:id → req.params.id)
  • req.query — query string parameters (/users?age=25 → req.query.age)
  • req.body — data sent in the request body (POST/PUT), needs body-parsing middleware like express.json()

Q44. How do you parse JSON and URL-encoded data in Express?

app.use(express.json());               // parses application/json
app.use(express.urlencoded({ extended: true })); // parses form data

Q45. What is express.static()?

Built-in middleware to serve static files (images, CSS, JS, HTML) from a directory.

app.use(express.static('public'));

SECTION 6: Express.js Intermediate

Q46. How do you handle errors in Express?

Using error-handling middleware (must have 4 parameters, placed after all routes):

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

And calling next(err) inside routes/middleware to forward errors:

app.get('/user/:id', async (req, res, next) => {
try {
const user = await getUser(req.params.id);
res.json(user);
} catch (err) {
next(err); // passed to error-handling middleware
}
});

Q47. How do you handle 404 (Not Found) routes in Express?

Add a catch-all middleware after all defined routes:

app.use((req, res) => {
res.status(404).json({ message: 'Route not found' });
});

Q48. What is CORS and how do you enable it in Express?

CORS (Cross-Origin Resource Sharing) is a security feature that restricts web pages from making requests to a different domain than the one serving the page. Enabled via the cors package:

const cors = require('cors');
app.use(cors()); // allow all origins
app.use(cors({ origin: 'https://example.com' })); // restrict origin

Q49. How do you handle sessions and cookies in Express?

const cookieParser = require('cookie-parser');
const session = require('express-session');
app.use(cookieParser());
app.use(session({
secret: 'mySecretKey',
resave: false,
saveUninitialized: true
}));

Q50. How do you implement authentication in Express (JWT-based)?

const jwt = require('jsonwebtoken');
// Generate token on login
const token = jwt.sign({ id: user.id }, 'secretKey', { expiresIn: '1h' });
// Middleware to protect routes
function auth(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'No token' });
try {
req.user = jwt.verify(token, 'secretKey');
next();
} catch (err) {
res.status(403).json({ message: 'Invalid token' });
}
}
app.get('/protected', auth, (req, res) => res.json({ data: 'secret data' }));

Q51. How do you validate incoming requests in Express?

Using libraries like express-validator or joi:

const { body, validationResult } = require('express-validator');
app.post('/user',
body('email').isEmail(),
body('password').isLength({ min: 6 }),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
// proceed
}
);

Q52. How do you handle file uploads in Express?

Using multer middleware:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ file: req.file });
});

Q53. How do you connect Express to a database (e.g., MongoDB with Mongoose)?

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');
const User = mongoose.model('User', new mongoose.Schema({
name: String,
email: String
}));
app.post('/users', async (req, res) => {
const user = await User.create(req.body);
res.status(201).json(user);
});

Q54. What is the order of execution for middleware in Express?

Middleware executes in the order it’s defined (top to bottom), unless a middleware doesn’t call next(), which halts the chain. This is why error-handling middleware and 404 handlers are typically defined last.

Q55. What are Template Engines in Express? Name a few.

Template engines let you generate dynamic HTML using server-side data. Examples: EJS, Pug (Jade), Handlebars.

app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index', { name: 'John' }));

SECTION 7: Express & Node — Deep / Advanced

Q56. How does Express handle asynchronous errors (Express 4 vs Express 5)?

In Express 4, errors thrown inside async route handlers are not automatically caught — you must manually wrap in try/catch and call next(err), or use a wrapper utility. In Express 5, async errors thrown inside route handlers/middleware are automatically forwarded to the error-handling middleware.

// Express 4 workaround
const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
app.get('/data', asyncHandler(async (req, res) => {
const data = await fetchData(); // if this throws, asyncHandler catches it
res.json(data);
}));

Q57. How would you structure a large-scale Express application (MVC pattern)?

project/
├── controllers/ # business logic
├── routes/ # route definitions
├── models/ # DB schemas
├── middlewares/ # custom middleware
├── config/ # DB, env configs
├── utils/ # helper functions
├── app.js
└── server.js

This separates concerns: routes define endpoints → call controllers → controllers use models for DB logic.

Q58. How do you implement rate limiting in Express?

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per window
});
app.use(limiter);

Q59. How do you secure an Express application?

  • Use helmet to set secure HTTP headers
  • Sanitize inputs to prevent NoSQL/SQL injection & XSS
  • Use HTTPS
  • Rate limiting
  • Validate/sanitize all user input
  • Use environment variables for secrets (dotenv)
  • Keep dependencies updated (npm audit)
  • CSRF protection for form-based apps

Q60. What is the difference between res.send(), res.json(), and res.end()?

  • res.send() — sends a response of various types (string, object, buffer); auto-sets Content-Type.
  • res.json() — sends a JSON response specifically, sets Content-Type to application/json.
  • res.end() — ends the response process without sending any additional data (low-level).

Q61. What is next('route') used for?

Calling next('route') skips the remaining middleware in the current route and moves to the next matching route (only works within app.METHOD() callbacks with multiple handlers).

Q62. How can you improve performance of a Node/Express application?

  • Use clustering / PM2 to leverage multi-core CPUs
  • Cache responses (Redis, in-memory caching)
  • Use compression middleware (compression)
  • Use a reverse proxy / load balancer (Nginx)
  • Avoid blocking the event loop (offload CPU-heavy work)
  • Use connection pooling for databases
  • Enable HTTP/2 and gzip compression
  • Use async I/O everywhere; avoid Sync methods

Q63. What is the difference between REST API and GraphQL (as it relates to Express)?

  • REST: Multiple endpoints, each returning fixed data structures; over-fetching/under-fetching is common.
  • GraphQL: Single endpoint, client specifies exactly what data it needs via queries — reduces over-fetching, often implemented in Express using express-graphql or apollo-server-express.

Q64. How does Express handle concurrent requests given Node’s single-threaded nature?

Each incoming request is handled asynchronously via the event loop. Since most operations (DB calls, file I/O) are non-blocking, the single thread can juggle many requests concurrently by delegating I/O work to libuv's thread pool / OS kernel and processing callbacks as they complete — it doesn't spawn a new thread per request like traditional multi-threaded servers.

Q65. What is the difference between PM2 and the Node.js cluster module?

cluster is a built-in module for basic multi-process scaling; PM2 is a production process manager built on top of these concepts, offering auto-restart on crash, load balancing, log management, zero-downtime reloads, and monitoring — used widely in production Node/Express deployments.

Q66. What is a Reverse Proxy and why is it used with Node/Express apps?

A reverse proxy (e.g., Nginx) sits in front of your Node app to handle tasks like SSL termination, load balancing, caching, gzip compression, and serving static files — offloading work from Node so it can focus on application logic.

Q67. How do you handle environment-specific configuration in Express apps?

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

require('dotenv').config();
const PORT = process.env.PORT || 3000;

Q68. What is the difference between app.all() and app.use()?

  • app.all() — matches all HTTP methods for a specific path.
  • app.use() — matches all HTTP methods for a path and all sub-paths (used mainly for middleware mounting).

Q69. How would you implement pagination in an Express + MongoDB API?

app.get('/posts', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const posts = await Post.find()
.skip((page - 1) * limit)
.limit(limit);
res.json(posts);
});

Q70. What is Idempotency in the context of REST APIs (relevant to Express routes)?

An idempotent operation produces the same result no matter how many times it’s called. GET, PUT, DELETE are idempotent by design; POST typically is not (each call may create a new resource).

--

--