Skip to main content

Junior NodeJS Interview Questions

Curated Junior-level NodeJS interview questions for developers targeting junior positions. 30 questions available.

Last updated:

NodeJS Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of NodeJS interview questions and answers. This page contains expertly curated interview questions covering all aspects of NodeJS, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our NodeJS interview questions are designed to help you:

  • Understand core concepts and best practices in NodeJS
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next NodeJS interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic NodeJS concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

30 questions
Q1:

What is the difference between synchronous and asynchronous file operations in Node.js?

Junior

Answer

Synchronous operations block the event loop until the task completes. Asynchronous operations allow Node to continue handling other requests while the file task runs in the background. Async is preferred to avoid blocking.
Quick Summary: Sync file ops (readFileSync, writeFileSync) block the event loop — the entire Node.js process freezes until the file operation completes. No other requests can be handled during that time. Async file ops (readFile, writeFile) hand the work off to libuv, return immediately, and call your callback when done. In a web server, always use async.
Q2:

What is the role of the event emitter?

Junior

Answer

Event emitters allow modules to emit events and let other parts of the app listen and react. It supports decoupled communication between components.
Quick Summary: EventEmitter is Node.js's built-in pub-sub mechanism. Objects that extend EventEmitter can emit named events (emitter.emit('data', value)) and listeners can subscribe (emitter.on('data', handler)). Many Node.js core modules (streams, http server, child processes) are EventEmitters. It's the foundation of event-driven architecture in Node.
Q3:

How does Node.js handle concurrency if it is single-threaded?

Junior

Answer

Node uses the event loop and worker threads behind the scenes. The main thread handles requests while heavy operations run in worker threads.
Quick Summary: Node.js is single-threaded for JavaScript, but libuv (its async I/O library) uses a thread pool for blocking operations like file system and DNS. The event loop delegates I/O to libuv, stays free to handle other events, and picks up the callback when libuv finishes. So concurrency is achieved through async I/O, not multiple threads.
Q4:

What is middleware chaining in Express.js?

Junior

Answer

Middleware chaining passes control from one middleware to another using next(), building a request pipeline for logging, parsing, authentication, etc.
Quick Summary: Middleware chaining in Express means each middleware calls next() to pass control to the next one in line. The chain runs in the order you define them: logging → authentication → body parsing → route handler. If any middleware doesn't call next() or send a response, the request just hangs. Order matters significantly.
Q5:

What is CORS and why is it needed?

Junior

Answer

CORS is a browser security rule restricting cross-domain requests. Node must configure CORS to allow approved domains to access APIs.
Quick Summary: CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks frontend code from making requests to a different domain. Your React app on localhost:3000 can't call your API on localhost:5000 without CORS headers. The server must send Access-Control-Allow-Origin headers to grant permission. The cors npm package makes this easy in Express.
Q6:

What is the difference between PUT and PATCH?

Junior

Answer

PUT replaces the entire resource, while PATCH updates only specific fields.
Quick Summary: PUT replaces the entire resource — you send the complete updated object and the server overwrites everything. PATCH partially updates — you send only the fields that changed. PUT is idempotent and clearer for full replacements; PATCH is more efficient when changing a single field in a large object.
Q7:

What is the purpose of Express.js router?

Junior

Answer

Routers organize routes into modules, improving structure and maintainability.
Quick Summary: Express Router lets you split routes into separate files and group related ones together. You create a router (const router = express.Router()), define routes on it, and mount it on a path (app.use('/api/users', userRouter)). Keeps your codebase organized — user routes in users.js, order routes in orders.js, etc.
Q8:

How does Node.js handle errors in asynchronous code?

Junior

Answer

Callbacks use error-first pattern. Async/await uses try/catch or .catch() with promises.
Quick Summary: In async code, errors propagate through Promise rejections and callback err parameters. In Express, passing an error to next(err) triggers error-handling middleware. Unhandled Promise rejections in older Node versions crashed the process silently — Node 15+ throws them as errors. Always use try/catch in async handlers and pass errors to next().
Q9:

What is a promise in Node.js?

Junior

Answer

A promise represents a future value and helps avoid callback nesting with cleaner chaining.
Quick Summary: A Promise is an object representing the eventual completion (or failure) of an async operation. Instead of nested callbacks (callback hell), you chain .then() and .catch(). A Promise is in one of three states: pending, fulfilled (resolved with a value), or rejected (rejected with an error). Cleaner than callbacks for async code.
Q10:

What is async/await and why is it useful?

Junior

Answer

async/await is syntax built on promises that makes asynchronous code look synchronous and easier to read.
Quick Summary: async/await is syntactic sugar over Promises that makes async code look like synchronous code. Mark a function async and use await inside it to pause execution until a Promise resolves. Errors throw naturally and are caught with try/catch. It dramatically improves readability compared to chained .then() calls.
Q11:

What is the purpose of the cluster module in Node.js?

Junior

Answer

Cluster creates multiple Node processes to use all CPU cores, improving performance.
Quick Summary: The cluster module lets you create multiple Node.js worker processes that all share the same server port. Since Node.js is single-threaded, cluster spawns one worker per CPU core — each worker handles its own event loop. The master process distributes incoming connections across workers. This is how Node.js uses all CPU cores.
Q12:

What is rate limiting in Node.js?

Junior

Answer

Rate limiting restricts how many requests a client can make in a given time to prevent abuse and overload.
Quick Summary: Rate limiting restricts how many requests a client can make in a given time window. Without it, a single client can spam your API with thousands of requests per second — slowing or crashing it. Use express-rate-limit to add: 100 requests per 15 minutes per IP. Essential for preventing abuse, DDoS, and brute-force attacks.
Q13:

What are HTTP status codes and why are they important?

Junior

Answer

Status codes indicate if a request succeeded or failed and help clients understand the response.
Quick Summary: HTTP status codes tell the client what happened: 200 (OK), 201 (Created), 400 (Bad Request — client error), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 500 (Internal Server Error). Returning the right status code helps clients handle responses correctly and makes APIs self-documenting and debuggable.
Q14:

What is streaming in Node.js?

Junior

Answer

Streaming processes data in chunks instead of loading it fully in memory. Useful for large files and real-time data.
Quick Summary: Streaming sends data in chunks as it's produced instead of buffering the entire response. For large files or real-time data, streaming means the client starts receiving data immediately — no waiting. Node.js streams pipe data from source to destination: readableStream.pipe(response) sends a file to the client without loading it all into memory.
Q15:

What is a template engine in Node.js?

Junior

Answer

A template engine creates dynamic HTML using variables. Examples: EJS, Pug, Handlebars.
Quick Summary: A template engine (EJS, Handlebars, Pug) renders HTML on the server by combining a template with data. Instead of sending JSON to a React frontend, you render HTML directly on the server and send it. Useful for traditional multi-page apps or email generation. Less common now that SPAs and APIs dominate.
Q16:

What is JSON Web Token (JWT)?

Junior

Answer

JWT is a compact token format for authentication, storing encoded user info verified using a secret or key.
Quick Summary: JWT is a compact, self-contained token for authentication. It contains three parts (header.payload.signature) — the payload carries user data (id, role), and the signature verifies it wasn't tampered with. Server issues a JWT on login; the client sends it in the Authorization header on subsequent requests. No session storage needed.
Q17:

What is the difference between global and local npm installation?

Junior

Answer

Global installs work everywhere; local installs stay inside a project folder.
Quick Summary: Global installation (npm install -g) installs the package for use as a CLI command anywhere on your machine — like installing nodemon globally. Local installation (npm install) installs into node_modules in the current project. For libraries you import in code, always install locally — global packages aren't part of your project's dependency tree.
Q18:

What is nodemailer and where is it used?

Junior

Answer

Nodemailer sends emails from Node apps, such as welcome emails or password resets.
Quick Summary: nodemailer is a Node.js library for sending emails from your app — sign-up confirmations, password resets, notifications. Configure it with your email provider (SMTP, Gmail, SendGrid) and call transporter.sendMail() with the recipient, subject, and body. It's the go-to email solution for Node.js backends.
Q19:

What is dotenv and why is it used?

Junior

Answer

dotenv loads environment variables from a .env file, keeping secrets out of source code.
Quick Summary: dotenv loads environment variables from a .env file into process.env. Instead of setting environment variables in your OS or CI pipeline for local development, you create a .env file with DATABASE_URL=xxx, add it to .gitignore (never commit it), and dotenv makes them available as process.env.DATABASE_URL when the app starts.
Q20:

What is body parsing in Express.js?

Junior

Answer

Body parsing converts request payloads to usable objects. express.json() handles JSON bodies.
Quick Summary: HTTP requests from clients arrive with bodies (JSON, form data, raw text). By default, Express doesn't parse them — you must add middleware. express.json() parses JSON bodies; express.urlencoded() parses form data. Without body parsing, req.body is undefined. These are included in Express 4.16+ — no need for the separate body-parser package.
Q21:

What is morgan in Node.js?

Junior

Answer

Morgan is a logging middleware that records request details.
Quick Summary: morgan is an HTTP request logger middleware for Express. It logs each incoming request — method, URL, status code, response time. Useful in development (see every request instantly) and production (audit trail). Multiple formats available: combined (Apache-style), dev (colored, concise), json. Pipe logs to a file or log aggregation service.
Q22:

How does Node.js handle database connections?

Junior

Answer

Connections use drivers or ORMs like MongoDB driver, Mongoose, or Sequelize with pooling for performance.
Quick Summary: Node.js database connections are typically managed with a connection pool — a set of pre-established connections shared across requests. Creating a new connection per request is slow; pools reuse existing ones. Libraries like pg (PostgreSQL), mysql2, and Mongoose manage this automatically. Configure pool size based on your database server's limits.
Q23:

What is the difference between SQL and NoSQL databases?

Junior

Answer

SQL uses tables and schemas; NoSQL uses flexible JSON-like documents or key-value stores.
Quick Summary: SQL databases (PostgreSQL, MySQL) store data in structured tables with strict schemas and support complex joins and transactions — great for relational data. NoSQL databases (MongoDB, Redis) store data in flexible formats (documents, key-value) without strict schemas — great for unstructured or rapidly evolving data and horizontal scaling.
Q24:

What is a RESTful API?

Junior

Answer

A RESTful API uses HTTP verbs and structured endpoints to perform operations.
Quick Summary: A RESTful API uses HTTP methods and URLs to represent resources and actions. GET /users retrieves users; POST /users creates one; PUT /users/1 updates user 1; DELETE /users/1 deletes it. REST APIs are stateless — each request is self-contained, not dependent on previous requests. They're the standard for web APIs.
Q25:

Why is logging important in Node apps?

Junior

Answer

Logging helps track errors, performance, and user actions. Winston and Pino are common tools.
Quick Summary: Logs are your visibility into what's happening in production. When something goes wrong, logs tell you when, what, and why. Log request errors, unexpected exceptions, slow queries, and key business events. In production, use a structured logger (Winston, Pino) and ship logs to a centralized system (Datadog, CloudWatch, ELK) for searching and alerting.
Q26:

What is the purpose of versioning an API?

Junior

Answer

Versioning prevents breaking old clients when adding new features.
Quick Summary: API versioning lets you make breaking changes without breaking existing clients. Include the version in the URL (/api/v1/users, /api/v2/users) or as a header. Old clients continue using v1; new clients use v2 with the new contract. Without versioning, every breaking change forces all clients to update simultaneously — risky and disruptive.
Q27:

What is the difference between require and import?

Junior

Answer

require is CommonJS; import is ES modules. Both load modules but with different syntax rules.
Quick Summary: require() is CommonJS — synchronous, loads at runtime, works everywhere in Node.js. import/export is ES Modules — asynchronous, static (evaluated at parse time), required for tree-shaking. In Node.js, ESM requires .mjs extension or "type": "module" in package.json. CommonJS is still more common; ESM is the future standard.
Q28:

What is Express error-handling middleware?

Junior

Answer

A special middleware with four parameters used to catch and manage errors in Express apps.
Quick Summary: Error-handling middleware in Express has four parameters (err, req, res, next) — Express knows it's an error handler by the arity. Define it last, after all routes. When you call next(err) anywhere, Express skips to this handler. It catches any error passed to next() and lets you format and return consistent error responses.
Q29:

What are static files in Node.js?

Junior

Answer

Static files like images, CSS, or JS are served as-is without processing.
Quick Summary: Static files are files served directly as-is — HTML, CSS, JavaScript, images, fonts. No server processing needed. In Express, use express.static('public') to serve everything in the public folder. The server just reads the file and sends it. This is typically handled by a CDN or reverse proxy (nginx) in production for better performance.
Q30:

What is the purpose of package-lock.json?

Junior

Answer

package-lock.json stores exact dependency versions for consistent installations.
Quick Summary: package-lock.json records the exact version of every installed package and all their sub-dependencies. While package.json might say "express: ^4.18.0" (any compatible version), package-lock.json pins it to the exact 4.18.2 that was installed. This ensures everyone on the team and CI/CD gets identical dependency trees.

Curated Sets for NodeJS

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice