0 / 20 read
All topics

Node.js

Node.js runtime, Express.js, APIs, middleware, streams, and server-side JavaScript

20 questions0 read8 interview prep

Questions12 shown

Node.js is a runtime environment that lets you run JavaScript outside the browser — on servers, your laptop, even IoT devices. It's built on Chrome's V8 engine, which compiles JavaScript directly into machine code.

Why developers love it:

JavaScript everywhere — Same language for frontend and backend. No context switching.

Non-blocking I/O — Node doesn't sit and wait for slow operations (like reading files or calling APIs). It moves on and comes back when the result is ready.

Blazing fast — V8 engine + event-driven architecture = speed.

NPM — The world's largest package ecosystem with over 2 million packages.

What Node.js is great for:

REST APIs and GraphQL servers

Real-time apps (chat, live notifications)

Microservices

CLI tools (like npm, eslint, prettier)

Streaming applications

What it's NOT great for:

Heavy CPU computations (video encoding, machine learning) — it's single-threaded, so long calculations block everything.

In short, Node.js made it possible for frontend developers to become full-stack developers using just one language.

The Event Loop is the heart of Node.js. It's what makes Node able to handle thousands of connections without creating thousands of threads.

The big picture:

Node.js is single-threaded. But it doesn't just do one thing at a time. When it hits a slow operation (file read, API call, database query), it hands it off to the system and moves on. When the result is ready, the callback gets added to a queue, and the Event Loop picks it up.

How it works (simplified):

Code
1. Your code runs (Call Stack)
2. Async operation starts  handed to OS/thread pool
3. Main thread continues with next code
4. Operation completes  callback added to queue
5. Event Loop checks: "Is the Call Stack empty?"
6. If yes  picks callback from queue  runs it
7. Repeat forever

The phases of the Event Loop:

| Phase | What runs |

|-------|-----------|

| Timers | setTimeout, setInterval callbacks |

| Pending | System-level callbacks (TCP errors, etc.) |

| Poll | I/O callbacks (file reads, network) |

| Check | setImmediate callbacks |

| Close | socket.on('close') callbacks |

Between every phase, Node processes:

process.nextTick() callbacks (highest priority)

Promise .then() callbacks (microtasks)

This is why process.nextTick always runs before setTimeout(fn, 0).

NPM (Node Package Manager) is two things:

1. A command-line tool for installing and managing packages

2. An online registry with over 2 million open-source packages

package.json is your project's manifest file. It describes:

Code
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  }
}

Key fields:

| Field | Purpose |

|-------|---------|

| name | Your project name |

| version | Follows SemVer (major.minor.patch) |

| scripts | Custom commands (npm run dev) |

| dependencies | Packages needed in production |

| devDependencies | Packages needed only for development |

Common commands:

npm init -y — Create package.json with defaults

npm install express — Add to dependencies

npm install -D nodemon — Add to devDependencies

npm ci — Clean install (for CI/CD, uses lockfile exactly)

package-lock.json locks exact versions of every dependency. Always commit it — it ensures everyone gets the same package versions.

Node.js supports two module systems. Here's the difference:

CommonJS (the classic way):

Code
// Exporting
module.exports = { add, subtract };
module.exports = function greet() {};

// Importing
const { add } = require('./math');
const express = require('express');

ES Modules (the modern way):

Code
// Exporting
export function add(a, b) { return a + b; }
export default function greet() {}

// Importing
import { add } from './math.js';
import express from 'express';

| Feature | CommonJS (require) | ES Modules (import) |

|---------|---------------------|----------------------|

| Loading | Synchronous | Asynchronous |

| When parsed | At runtime | At parse time (static) |

| Tree-shaking | Not possible | Possible (smaller bundles) |

| Top-level await | No | Yes |

| Default in Node | .js files | .mjs files or "type": "module" |

How to use ES Modules in Node.js:

1. Use .mjs file extension, OR

2. Add "type": "module" in your package.json

Tip: Most modern projects use ES Modules. If you're starting a new project, go with import/export.

Express.js is the most popular web framework for Node.js. It takes the bare-bones http module and adds powerful features like routing, middleware, and easy request handling.

Creating a basic server:

Code
import express from 'express';
const app = express();

// Middleware to parse JSON
app.use(express.json());

// Routes
app.get('/', (req, res) => {
  res.json({ message: 'Hello World!' });
});

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;   // URL parameter
  const sort = req.query.sort;     // Query string ?sort=name
  res.json({ userId, sort });
});

app.post('/users', (req, res) => {
  const userData = req.body;       // Request body
  res.status(201).json(userData);
});

// Start server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Why Express?

Minimal and unopinionated — you structure your app how you want

Huge middleware ecosystem (cors, helmet, morgan)

Dead simple routing

Works perfectly with any database

Key methods:

app.get(), app.post(), app.put(), app.delete() — Route handlers

app.use() — Apply middleware

req.params, req.query, req.body — Access request data

res.json(), res.send(), res.status() — Send responses

**Middleware** is a function that sits between the incoming request and the final response. Think of it as a pipeline — each middleware does its job and passes the request along. [code block] **The ...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

This is one of the most important concepts in Node.js. **Blocking I/O** — The program **stops and waits** until the operation finishes: [code block] **Non-Blocking I/O** — The program **continues**...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

**Streams** let you process data **piece by piece** instead of loading everything into memory at once. Think of it like watching a video — you don't download the entire movie first, you stream it chun...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

Good error handling is the difference between a production-ready app and a "works on my machine" app. **1. Try/Catch for async/await:** [code block] **2. Express error middleware:** [code block] **...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

**CORS** (Cross-Origin Resource Sharing) is a browser security feature that **blocks requests from a different origin** than the one that served the page. **Example:** Your React app runs on `http://...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

The `process` object is a **global** object that gives you information about and control over the current Node.js process. **Most useful properties:** [code block] **Event listeners:** [code block]...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

**Environment variables** keep sensitive data (API keys, database URLs, secrets) out of your code. **Using a .env file with dotenv:** [code block] [code block] **Best practices:** 1. **Never commi...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

Interview Preparation

Premium

High-signal questions that come up most in real interviews. These are the ones worth spending extra time on.

**JWT (JSON Web Token)** is the most common way to handle authentication in APIs. Here's the complete flow: **1. User signs in:** [code block] **2. Client stores the token** and sends it with every ...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

A well-designed REST API is a joy to use. Here are the key principles: **1. Use nouns for endpoints, not verbs:** [code block] **2. Use proper HTTP methods:** | Method | Purpose | Example | |-------...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

Node.js is single-threaded, which means **CPU-heavy tasks block everything**. Worker Threads solve this by letting you run JavaScript in **parallel threads**. [code block] [code block] **When to us...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

This is a classic Node.js interview question. All three schedule code to run "later," but the **when** is different. **Execution order:** [code block] **Inside an I/O callback, the order is guarante...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

The `fs` module handles everything file-related. Always prefer the **async/Promise** versions in server code. **Reading files:** [code block] **Writing files:** [code block] **Other common operatio...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

Since Node.js is single-threaded, it only uses **one CPU core** by default. The **Cluster module** lets you create multiple worker processes that share the same port — using all available CPU cores. ...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

Database connection management is crucial for performance and reliability. **MongoDB with Mongoose (recommended pattern):** [code block] **Why this pattern?** - **Connection pooling** — Mongoose mai...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.

Security should never be an afterthought. Here are the essential practices: **1. Use Helmet for HTTP headers:** [code block] **2. Validate and sanitize all input:** [code block] **3. Hash passwords...

Sign in to continue reading

Create a free account to unlock login-level content, or go premium for everything.