# Top 50 Node.js Interview Questions and Answers

#### 1\. What is Node.js and how does it work?

Node.js is a runtime environment built on Chrome's V8 JavaScript engine. It executes JavaScript code outside the browser and uses an event-driven, non-blocking I/O model.

---

#### 2\. What is the event loop in Node.js?

The event loop handles asynchronous operations in Node.js. It continuously checks the event queue and executes callbacks once the stack is clear.

---

#### 3\. What is the difference between synchronous and asynchronous code in Node.js?

Synchronous code blocks execution until the task completes. Asynchronous code allows other operations to continue while the task executes, using callbacks or promises.

---

#### 4\. Explain how non-blocking I/O works in Node.js.

Node.js uses non-blocking I/O to perform operations (like reading files or making API calls) without waiting for the response, using callbacks, promises, or async/await.

---

#### 5\. What are the key features of Node.js?

* Non-blocking I/O
    
* Event-driven architecture
    
* Single-threaded
    
* Fast execution using V8 engine
    
* Rich NPM ecosystem
    

---

#### 6\. What is the difference between `setImmediate()` and `process.nextTick()`?

`process.nextTick()` executes after the current operation completes, before I/O events. `setImmediate()` executes in the next event loop iteration.

---

#### 7\. How does Node.js handle child processes?

Node.js uses the `child_process` module to spawn subprocesses using `spawn`, `exec`, or `fork`.

---

#### 8\. What are streams in Node.js?

Streams are abstract interfaces for working with streaming data. Types: Readable, Writable, Duplex, and Transform.

---

#### 9\. What are buffers in Node.js?

Buffers handle raw binary data directly in memory, mostly used with streams.

---

#### 10\. How is Node.js different from JavaScript in the browser?

Node.js has access to file systems, networking, and OS-level APIs, while browser JavaScript is sandboxed and limited to DOM.

---

#### 11\. What is the difference between CommonJS and ES Modules?

CommonJS uses `require()` and `module.exports`. ES Modules use `import` and `export` and are standard in modern JavaScript.

---

#### 12\. How does `require()` work in Node.js?

`require()` loads modules synchronously. It caches the module after the first load.

---

#### 13\. What is the purpose of `package.json`?

It defines metadata about a Node.js project, including dependencies, scripts, and entry points.

---

#### 14\. What is the difference between `dependencies` and `devDependencies`?

`dependencies` are needed in production. `devDependencies` are needed only during development (e.g., testing tools).

---

#### 15\. What is a peer dependency?

Peer dependencies specify which versions of a package your project is compatible with, often used in plugins.

---

#### 16\. How can you create a custom module in Node.js?

Create a JS file, define functions, and export them using `module.exports`.

---

#### 17\. What is the use of `npx`?

`npx` runs a package without installing it globally. Useful for executing CLI tools.

---

#### 18\. How do you read/write files using the `fs` module?

```js
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {});
fs.writeFile('file.txt', 'Hello', (err) => {});
```

---

#### 19\. What's the difference between `fs.readFile` and `fs.readFileSync`?

`fs.readFile` is asynchronous. `fs.readFileSync` is blocking and halts further execution.

---

#### 20\. How do you handle large file uploads in Node.js?

Use streams to handle large files efficiently without loading them fully into memory.

---

#### 21\. What does the `path` module do in Node.js?

It provides utilities for working with file and directory paths.

---

#### 22\. How do you create a basic HTTP server in Node.js?

```js
const http = require('http');
const server = http.createServer((req, res) => {
  res.end('Hello');
});
server.listen(3000);
```

---

#### 23\. What is the `http` module in Node.js?

It allows Node.js to transfer data over HTTP. Used to create servers and make requests.

---

#### 24\. How does Express.js simplify server-side development?

Express provides routing, middleware, and utility functions to simplify API and web app development.

---

#### 25\. How do you handle file uploads in Node.js?

Use `multer` middleware in Express to handle file uploads.

---

#### 26\. What is Express.js and why is it used?

Express is a minimalist web framework for Node.js, used to create web applications and APIs easily.

---

#### 27\. What are middleware functions in Express.js?

Functions that execute before the final route handler. Used for logging, auth, parsing, etc.

---

#### 28\. How do you handle routing in Express.js?

Use methods like `app.get()`, [`app.post`](http://app.post)`()`, and define routes with paths and handlers.

---

#### 29\. How do you handle errors in Express?

Use middleware with 4 parameters: `(err, req, res, next) => {}`

---

#### 30\. What is the difference between `app.use()` and `app.get()`?

`app.use()` applies middleware to all routes. `app.get()` handles only GET requests for a specific path.

---

#### 31\. How do you create a RESTful API in Node.js?

Use Express routes to define endpoints for CRUD operations and use proper HTTP methods.

---

#### 32\. How do you connect a Node.js app to MongoDB/PostgreSQL?

Use ODMs/ORMs like Mongoose (MongoDB) or MikroORM/Prisma (PostgreSQL). Configure DB URL and initialize connection.

---

#### 33\. What are status codes like 200, 404, 500 used for?

They indicate the HTTP response result. 200 = OK, 404 = Not Found, 500 = Server Error.

---

#### 34\. What are query params vs path params in an API?

* Path param: `/user/:id` (used for resource ID)
    
* Query param: `/user?id=123` (used for filters, search)
    

---

#### 35\. How do you protect APIs using middleware (like API keys or JWT)?

Create auth middleware that checks for API key or JWT in headers before processing the route.

---

#### 36\. What is a callback?

A function passed as an argument to another function, called after the parent function completes.

---

#### 37\. What are Promises and how do they work?

Promises represent the result of an async operation. They have `then`, `catch`, and `finally` handlers.

---

#### 38\. What is `async/await` and how is it better than Promises?

`async/await` simplifies promise chaining and makes async code look synchronous.

---

#### 39\. How do you handle errors in async/await?

Use `try...catch` blocks around `await` calls.

---

#### 40\. What is the difference between `Promise.all`, `Promise.any`, and `Promise.race`?

* `Promise.all`: resolves when all succeed
    
* `Promise.any`: resolves when the first one succeeds
    
* `Promise.race`: resolves/rejects on the first settled promise
    

---

#### 41\. How do you debug a Node.js application?

Use `console.log`, `debugger`, or Node.js Inspector (e.g., `node --inspect index.js`).

---

#### 42\. What is `nodemon` and why is it useful?

`nodemon` watches file changes and restarts your Node.js server automatically. Useful in development.

---

#### 43\. What are common ways to log and monitor a Node.js app in production?

Use logging tools like Winston, Morgan, or services like LogRocket, Sentry, Datadog.

---

#### 44\. What is the use of `dotenv`?

To load environment variables from a `.env` file into `process.env`.

---

#### 45\. How do you handle environment variables in Node.js?

Use the `dotenv` package and access variables using `process.env.VAR_NAME`.

---

#### 46\. What are some common security practices in Node.js?

* Validate inputs
    
* Use HTTPS
    
* Handle errors properly
    
* Avoid exposing secrets
    
* Use helmet and rate limiting
    

---

#### 47\. How do you prevent XSS or SQL Injection in an Express app?

* Use input sanitization libraries
    
* Use ORM query builders (like Prisma, MikroORM)
    
* Escape user inputs
    

---

#### 48\. What is CORS and how do you handle it in Node.js?

CORS (Cross-Origin Resource Sharing) allows or blocks requests from other origins. Use the `cors` middleware in Express.

---

#### 49\. How do you improve performance of a Node.js application?

* Use async operations
    
* Optimize DB queries
    
* Use caching (Redis)
    
* Minimize middleware
    

---

#### 50\. What’s the difference between `process.env.NODE_ENV === 'production'` and development mode?

In production, certain behaviors (like logging or error messages) are disabled or optimized. Use this check to control config for prod/dev.
