Node.js Interview Questions: The Screening Round

50 Essential Beginner Node.js Interview Questions & Answers frequently asked by top MNCs.

Beginner Level (Q1 – Q50)

Q01
What is Node.js?
Beginner

Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome’s V8 JavaScript engine. It allows developers to execute JavaScript on the server-side, outside of a web browser.

Real-World Example: Imagine you want to build the backend for a chat application like WhatsApp. Node.js allows you to use JavaScript to handle thousands of users sending messages to your server in real-time.
Q02
How does Node.js differ from JavaScript in the browser?
Beginner

Browser JS interacts with the DOM (Document Object Model), handles UI events, and has no direct access to the OS. Node.js lacks the DOM but has direct access to the operating system, file system, and network interfaces via built-in modules.

Real-World Example: You cannot write a script in Chrome that silently reads a user’s local `C:/passwords.txt` file (for security). In Node.js, you can build a desktop app or server script that freely reads and writes to local hard drives.
Q03
What is the V8 Engine?
Beginner

V8 is Google’s open-source high-performance JavaScript and WebAssembly engine, written in C++. It compiles JavaScript directly into native machine code rather than interpreting it in real-time.

Problem Scenario: JS is naturally slow because it’s an interpreted language. Node.js leverages V8 to compile JS into fast machine code, allowing a Node server to perform complex calculations fast enough to serve thousands of concurrent API requests.
Q04
What is meant by “Non-blocking I/O”?
Beginner

Non-blocking I/O means that the Node.js process does not halt (block) when performing Input/Output operations like reading a file or querying a database. It delegates the task and continues executing subsequent code.

Real-World Example: Think of a waiter in a restaurant. Instead of waiting at the kitchen counter for your food to cook (blocking), the waiter submits your ticket and immediately goes to take orders from other tables (non-blocking).
Q05
Is Node.js single-threaded or multi-threaded?
Beginner

Node.js operates on a single main thread using an event loop. However, behind the scenes, it utilizes a C++ library called `libuv` which maintains a thread pool to handle heavy asynchronous I/O tasks.

Real-World Example: Your Express API has one main thread taking HTTP requests. If a request requires a heavy file system read, Node offloads it to the hidden thread pool, keeping the main thread free to accept new user logins.
Q06
What is the Event Loop?
Beginner

The Event Loop is the mechanism that allows Node.js to perform non-blocking I/O operations despite being single-threaded. It constantly monitors the call stack and callback queue, pushing resolved asynchronous callbacks onto the stack when it’s empty.

Real-World Example: It acts like an air traffic controller. It ensures standard code runs first, and queues up “delayed” tasks (like database responses) for landing only when the runway (call stack) is clear.
Q07
What is NPM?
Beginner

NPM stands for Node Package Manager. It consists of a massive online registry of open-source JavaScript tools/libraries, and a command-line utility used to install and manage these packages in your project.

Real-World Example: Instead of writing a complex date-formatting function from scratch, you run `npm install date-fns` to instantly download and use pre-written, tested code from the community.
Q08
What is the purpose of `package.json`?
Beginner

It is the manifest file of a Node.js project. It holds metadata like the project’s name, version, author, custom scripts, and most importantly, the lists of dependencies (packages) required to run the application.

Problem Scenario: If you share your code with a coworker, they don’t need your massive `node_modules` folder. They just need your `package.json`. They run `npm install`, and npm reads this file to download exact versions of every necessary library.
Q09
What is the difference between `dependencies` and `devDependencies`?
Beginner

`dependencies` are packages required for the application to run in production (e.g., Express, Mongoose). `devDependencies` are only needed for local development and testing (e.g., Jest, Nodemon, ESLint).

Real-World Example: A testing framework like Jest helps you test your app locally (`devDependency`). But when you deploy your app to an AWS server, the server only needs Express to run the API (`dependency`), ignoring Jest to save space and memory.
Q10
What is a Callback?
Beginner

A callback is a function passed as an argument into another function. In Node.js, callbacks are heavily used to execute code only after an asynchronous operation has completed.

Real-World Example: `fs.readFile(‘data.txt’, (err, data) => { console.log(data); });` — The anonymous function is the callback. Node goes to read the file, and “calls back” this function only when the hard drive finally returns the text.
Q11
What is “Callback Hell”?
Beginner

Callback Hell (or the Pyramid of Doom) occurs when multiple asynchronous operations depend on each other, leading to deeply nested, unreadable, and hard-to-maintain callback functions.

Problem Scenario: You need to 1) Find a user in a DB, then 2) Use their ID to find their orders, then 3) Use order IDs to find shipping details. Nesting these 3 callbacks makes the code indent into a shape of a sideways triangle, making bug-hunting a nightmare.
Q12
How do Promises solve Callback Hell?
Beginner

A Promise represents the eventual completion (or failure) of an asynchronous operation. Instead of nesting callbacks, Promises allow you to chain `.then()` and `.catch()` blocks, flattening the code structure.

Real-World Example: `getUser().then(getOrders).then(getShipping).catch(handleError)`. This reads top-to-bottom like a plain English sentence, making complex DB queries vastly easier to maintain.
Q13
What is `async/await`?
Beginner

Introduced in ES8, `async/await` is syntactic sugar over Promises. It allows developers to write asynchronous code that visually looks and behaves like synchronous, blocking code, while remaining non-blocking under the hood.

Real-World Example: Instead of `.then()`, you write `const user = await getUser();`. The execution logically pauses on that line until the DB returns the user, keeping your code exceptionally clean.
Q14
What is the `fs` module?
Beginner

The `fs` (File System) is a core Node.js module used to interact with the file system. It provides methods to read, write, update, delete, and rename files.

Problem Scenario: If you are building an error logging system, you use `fs.appendFile()` to write crash details into an `error.log` text file on the server’s hard drive so developers can review it later.
Q15
What is the difference between `fs.readFile` and `fs.readFileSync`?
Beginner

`readFile` is asynchronous and non-blocking, requiring a callback. `readFileSync` is synchronous and blocking; it completely halts the Node process until the file is fully read.

Problem Scenario: Never use `readFileSync` inside an API endpoint (e.g., when a user logs in). If the file takes 2 seconds to read, no other user in the world can access your server for those 2 seconds. Use it only for initial server startup configs.
Q16
What is the `path` module?
Beginner

The `path` module provides utilities for working with file and directory paths. It is essential because different operating systems use different path separators (Windows uses `\` while Linux/Mac uses `/`).

Real-World Example: `path.join(__dirname, ‘public’, ‘index.html’)` automatically constructs the correct file path regardless of whether your app is running on a developer’s Windows PC or an AWS Linux server.
Q17
What is the `http` module?
Beginner

The `http` module is a core module that allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). It can be used to create an HTTP server that listens to server ports and gives a response back to the client.

Real-World Example: While most developers use Express.js today, Express is actually just a framework built entirely on top of Node’s native `http.createServer()` method to handle web traffic.
Q18
What are EventEmitters?
Beginner

The `EventEmitter` class (from the `events` module) is used to trigger and listen to custom events. You use `.on()` to listen for an event and `.emit()` to trigger it.

Real-World Example: In a chat app backend, when a new socket connection is made, you can `emitter.emit(‘userJoined’, userData)`. Various distinct parts of your app listening to `.on(‘userJoined’)` can log the event, send a welcome email, and update the active user count independently.
Q19
What are Streams in Node.js?
Beginner

Streams are objects that let you read data from a source or write data to a destination in continuous, small chunks rather than loading the entire payload into RAM at once.

Problem Scenario: If you need to send a 2GB video file to a user, doing `fs.readFile` will load 2GB into the server’s RAM. If 10 users request it, the server crashes. Using `fs.createReadStream` sends the video frame-by-frame, using almost zero RAM.
Q20
What are the 4 types of Streams?
Beginner

1) Readable (read data), 2) Writable (write data), 3) Duplex (both read and write), 4) Transform (read, modify, and write).

Real-World Example: A video upload is a Readable stream from the user. You pipe it through a Transform stream to compress it (zip it). Finally, you pipe it to a Writable stream to save it to your hard drive.
Q21
What is a Buffer?
Beginner

A Buffer is a temporary storage spot for a chunk of raw binary data. It is primarily used by streams to hold data while it is being transferred from one place to another.

Real-World Example: Think of a Buffer like a roller coaster car. People (data bytes) load into the car. The car doesn’t move until it’s full (Buffer is full). Once full, it’s sent off to be processed, and an empty car takes its place.
Q22
What is the `process` object?
Beginner

The `process` object provides information about, and control over, the current Node.js process. It is a global object, meaning it is available everywhere without importing.

Real-World Example: You frequently use `process.env.PORT` to let cloud providers like Heroku or AWS assign a dynamic port to your app, or `process.exit(1)` to force the server to shut down if a critical database connection fails.
Q23
What is Express.js?
Beginner

Express.js is a minimal and flexible Node.js web application framework. It provides a robust set of features for building web and mobile APIs quickly, handling routing, requests, and responses efficiently.

Problem Scenario: Writing an API with Node’s raw `http` module requires manually parsing URLs and headers with hundreds of lines of code. Express reduces a full API endpoint down to a simple `app.get(‘/users’, (req, res) => {…})`.
Q24
What is Middleware in Express?
Beginner

Middleware functions are functions that have access to the request object (`req`), the response object (`res`), and the `next` middleware function in the application’s request-response cycle. They can execute code, make changes to req/res, or end the cycle.

Real-World Example: A bouncer at a club. The user requests to enter (`req`). The middleware checks if they have a valid JSON Web Token. If yes, it calls `next()` to let them into the route. If not, the middleware returns `res.status(401)` and kicks them out.
Q25
What is CORS?
Beginner

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers. By default, a browser won’t let a frontend (e.g., your-react-app.com) make API calls to a backend on a different domain (e.g., your-node-api.com) unless the backend explicitly allows it via CORS headers.

Problem Scenario: If you try to fetch data from your Node API in a browser and get a red CORS error in the console, you fix it in Node by installing the `cors` package and adding `app.use(cors())` to explicitly allow cross-origin requests.
Q26
What is the difference between `req.params` and `req.query`?
Beginner

`req.params` contains route parameters (part of the URL path), while `req.query` contains URL query string parameters (everything after the `?` in the URL).

Real-World Example: In the URL `/users/123/shoes?color=blue`, `123` is a param (`req.params.id`), used to identify the specific user. `blue` is a query (`req.query.color`), used to filter the data.
Q27
How do you parse incoming JSON data in Express?
Beginner

You use the built-in middleware `express.json()`. Without this, if a client sends a JSON payload (like a signup form) via a POST request, `req.body` will be undefined.

Problem Scenario: Before an Express route can read `req.body.password` from a frontend React form, it must pass through `app.use(express.json())` which translates the raw HTTP byte stream into a readable JavaScript object.
Q28
What is `dotenv`?
Beginner

`dotenv` is a zero-dependency module that loads environment variables from a `.env` file into `process.env`.

Problem Scenario: You must never hardcode database passwords or AWS secret keys directly into your JavaScript files, because pushing to GitHub exposes them. You store them locally in a `.env` file (which is ignored by Git) and access them via `process.env.DB_PASS`.
Q29
What is `nodemon`?
Beginner

`nodemon` is a development utility that monitors your project for any file changes and automatically restarts your Node.js server.

Real-World Example: Without nodemon, every time you fix a typo in your API code, you must switch to the terminal, press `Ctrl+C` to stop the server, and type `node index.js` again. Nodemon does this instantly every time you hit Save (`Ctrl+S`).
Q30
How do you handle routing in Express?
Beginner

Express uses methods corresponding to HTTP verbs (e.g., `app.get()`, `app.post()`). For organizing complex apps, Express provides `express.Router()` to create modular, mountable route handlers.

Real-World Example: Instead of having 500 routes in `index.js`, you create a `users.route.js` file using `Router()`, and mount it in your main file using `app.use(‘/users’, userRoutes)`. This keeps large enterprise codebases clean.
Q31
What is an uncaught exception in Node.js?
Beginner

An uncaught exception is a JavaScript error that is thrown but not caught in a `try/catch` block. By default, this immediately crashes the Node.js process.

Problem Scenario: If you attempt to run `user.name.toUpperCase()` but `user` is accidentally null, Node throws an error. If there is no `try/catch`, your entire server goes offline for every user until it is manually restarted.
Q32
What is `Promise.all()`?
Beginner

`Promise.all()` takes an array of promises and runs them concurrently, returning a single Promise that resolves when all of the promises have resolved (or rejects if any one of them fails).

Real-World Example: A dashboard needs user profile data, recent orders, and notifications. Instead of waiting for them one by one (taking 3 seconds total), you put them in `Promise.all()`. They fetch simultaneously, taking only 1 second total.
Q33
Difference between CommonJS and ES Modules in Node?
Beginner

CommonJS uses `require()` and `module.exports` and is loaded synchronously. ES Modules (ESM) use `import` and `export`, are standard across browsers and modern JS, and are loaded asynchronously.

Problem Scenario: Historically Node only supported CommonJS. Now, to use modern `import express from ‘express’`, you must add `”type”: “module”` to your `package.json` file.
Q34
What happens if you block the Event Loop?
Beginner

Because Node is single-threaded, running a heavy, blocking synchronous task (like a massive mathematical `while` loop) prevents the Event Loop from processing any new incoming network requests.

Problem Scenario: If User A triggers a route that generates a massive PDF report synchronously (taking 10 seconds), the thread is blocked. User B, trying to simply log in at the same time, will see a loading spinner for 10 seconds until User A’s task finishes.
Q35
What is `setTimeout` vs `setImmediate`?
Beginner

`setTimeout(fn, 0)` schedules a script to run after a minimum threshold in ms. `setImmediate(fn)` schedules a script to run immediately after the current phase of the Event Loop (I/O polling) is complete.

Real-World Example: Use `setImmediate` when you have a heavy CPU operation that you want to break into smaller chunks, allowing I/O operations (like incoming requests) to squeeze in between the chunks so the server doesn’t freeze.
Q36
What is `process.nextTick()`?
Beginner

`process.nextTick()` schedules a callback function to be executed exactly after the current operation completes, but before the Event Loop moves on to the next phase.

Real-World Example: It acts like an absolute VIP pass. If you have an error event that absolutely must be handled before the server attempts to read any more files, `nextTick` forces that callback to execute immediately.
Q37
How do you connect a database to Node.js?
Beginner

Node interacts with databases using specific driver packages installed via npm. Common choices are `mongoose` for MongoDB, `pg` for PostgreSQL, or ORMs like `Prisma` or `Sequelize`.

Real-World Example: By installing `mongoose`, you can create rigid models for your NoSQL data and use simple methods like `User.find()` to fetch data without writing complex native queries.
Q38
What is JWT (JSON Web Token)?
Beginner

JWT is a standard for securely transmitting information between a client and a server as a JSON object. It is most commonly used for stateless user authentication.

Real-World Example: A user logs in. The Node server verifies the password and generates a JWT string containing their UserID, signed with a secret key. The frontend sends this token in headers on future requests. Express middleware verifies the signature to know who the user is without checking the DB.
Q39
Why use `bcrypt` for passwords?
Beginner

`bcrypt` is a library used to securely hash passwords. Hashing is a one-way mathematical function. You cannot “decrypt” a hash back to the original password.

Problem Scenario: If your DB is hacked, storing plain text passwords (`”password123″`) exposes all your users. `bcrypt` turns it into `$2b$10$xyz…`. Even if stolen, the hacker cannot reverse it to find the real password.
Q40
What is Helmet.js?
Beginner

Helmet is a middleware package for Express that automatically secures your application by setting various HTTP response headers.

Real-World Example: By simply adding `app.use(helmet())`, it hides the `X-Powered-By: Express` header (so hackers don’t know you use Node) and implements XSS protection headers to stop malicious script injections.
Q41
What is Semantic Versioning (SemVer)?
Beginner

SemVer is a versioning system used in `package.json` denoted by three numbers: MAJOR.MINOR.PATCH (e.g., `1.4.2`).

Real-World Example: `PATCH` (1.4.3) means bug fixes. `MINOR` (1.5.0) means new features but backwards compatible. `MAJOR` (2.0.0) means breaking changes. Knowing this prevents you from updating an npm package that breaks your entire API.
Q42
What is the purpose of `package-lock.json`?
Beginner

While `package.json` specifies acceptable version ranges (e.g., `^1.4.0`), `package-lock.json` records the exact, precise version of every dependency and sub-dependency that was actually installed.

Problem Scenario: “It works on my machine but crashes in production.” This happens when devs have slightly different minor versions of a library. The lock file forces all developers and deployment servers to install identical byte-for-byte dependencies.
Q43
What is the `cluster` module?
Beginner

The `cluster` module allows you to easily create child processes (workers) that run simultaneously and share the same server port. This takes advantage of multi-core systems.

Real-World Example: Node is single-threaded. If you run it on an 8-core AWS server, 7 cores are asleep. Using `cluster`, you fork your app 8 times. Now 8 Node instances share the traffic, handling 8 times as many requests simultaneously.
Q44
What are Worker Threads?
Beginner

Introduced to handle CPU-intensive tasks, the `worker_threads` module allows Node.js to execute JavaScript in parallel using isolated V8 environments, without blocking the main event loop.

Problem Scenario: If your app needs to resize uploaded images (heavy CPU math), doing it on the main thread blocks all HTTP requests. Sending the task to a Worker Thread keeps the main thread fast and responsive.
Q45
How do you prevent SQL Injection / NoSQL Injection in Node?
Beginner

Never concatenate raw user input directly into database query strings. Always use parameterized queries (prepared statements) or use an ORM/ODM (like Mongoose or Prisma) which sanitizes inputs automatically.

Real-World Example: In Postgres via Node, instead of `query(“SELECT * FROM users WHERE email = ‘” + req.body.email + “‘”)`, you use parameterization: `query(“SELECT * FROM users WHERE email = $1”, [req.body.email])` to render malicious SQL syntax harmless.
Q46
How do you debug a Node.js application?
Beginner

While `console.log()` is common, professional debugging is done by starting Node with the `–inspect` flag, or by using the built-in debugging tools in an IDE like VS Code to set breakpoints.

Real-World Example: By clicking the margin in VS Code to create a red dot (breakpoint) and attaching the debugger, the server will freeze at that exact line of code during a request, allowing you to inspect variable values in real-time.
Q47
What is an API?
Beginner

Application Programming Interface. In the context of Node, it’s a set of URL endpoints that allow frontend applications (like React, or a mobile app) to communicate with your backend logic and database.

Real-World Example: An iOS app doesn’t connect to a database directly. It makes an HTTP request to your Node API at `api.yoursite.com/users`, and your Node API handles the secure database fetching and returns JSON.
Q48
What is REST?
Beginner

Representational State Transfer (REST) is a software architectural style. A RESTful API relies on standard HTTP methods (GET, POST, PUT, DELETE) linked to specific URLs (resources) in a stateless manner.

Real-World Example: `GET /articles` fetches all articles. `POST /articles` creates one. `DELETE /articles/5` deletes article #5. It relies on standard conventions that any frontend developer will immediately understand.
Q49
What is global installation of an npm package?
Beginner

By using the `-g` flag (`npm install -g package-name`), the package is installed on your operating system globally, rather than in the local `node_modules` of a specific project. This is usually reserved for CLI tools.

Real-World Example: You install `nodemon` or the `angular-cli` globally so you can type those commands directly into any terminal window on your machine, regardless of what folder you are in.
Q50
What are Memory Leaks in Node.js?
Beginner

A memory leak occurs when a Node app allocates memory (RAM) but fails to release it back to the OS when it’s no longer needed (garbage collection failure). Over time, RAM fills up and the server crashes.

Problem Scenario: Storing user session data in a global JavaScript array `const sessions = []` instead of a database like Redis. Every user login adds to the array. The array never clears. Eventually, it consumes all 2GB of server RAM and the process dies.