Node.js topics
Everything a junior developer needs for a Node.js interview, in simple words. Go in order, or pick any topic from the list.
Q&A practice
Interview questions with short answers. Try to answer in your own words first, then open the answer. Mark the ones you know.
No questions match. Try a different search or filter.
Diagrams
Pictures of how Node.js works inside, and how common flows move step by step. Draw these on a whiteboard in an interview and you will stand out.
The diagrams could not load. Check your internet connection, then open this tab again.
Node.js architecture
Your code sits on top. Node.js core modules call C++ code, which talks to V8 (runs JavaScript) and libuv (does async work). libuv uses the operating system and a small thread pool.
flowchart TB app["Your JavaScript code"] api["Node.js core modules: fs, http, crypto, stream"] bind["C++ bindings"] v8["V8 engine: runs your JavaScript"] uv["libuv: event loop and async I/O"] pool["Thread pool: 4 threads by default"] os["Operating system: files, network, timers"] app --> api api --> bind bind --> v8 bind --> uv uv --> pool uv --> os pool --> os
Event loop phases
The event loop goes around in a circle. In each turn it visits these phases in order. Between phases, Node.js empties the nextTick queue first, then the promise queue.
flowchart TD A["1. timers: setTimeout and setInterval callbacks"] --> B["2. pending callbacks: some system errors"] B --> C["3. idle and prepare: internal use"] C --> D["4. poll: I/O callbacks, waits for new I/O"] D --> E["5. check: setImmediate callbacks"] E --> F["6. close callbacks: socket.on close"] F --> A M["After every callback: process.nextTick queue, then promise microtasks"] M -.-> D
Who runs first?
This is the order for almost every "what is the output?" question. Normal code always finishes first. Then nextTick, then promises. Timers and setImmediate come last.
flowchart LR s["1. Normal code runs first"] --> t["2. process.nextTick queue"] t --> p["3. Promise callbacks"] p --> l["4. Event loop phases: timers, I/O, setImmediate"]
How Node.js handles one request without waiting
The main thread starts the database query and does not wait. While the database works, Node.js can handle other requests. When the result is ready, the event loop runs your callback.
sequenceDiagram participant C as Client participant N as Node main thread participant D as Database C->>N: HTTP request N->>N: Run route handler N->>D: Start query, do not wait Note over N: Main thread is free for other requests D-->>N: Query result is ready N->>N: Event loop runs the callback N-->>C: HTTP response
Blocking vs non-blocking code
Blocking code makes every other request wait. Non-blocking code starts the slow work and moves on. This is the main reason to avoid sync functions like readFileSync inside a server.
flowchart LR
subgraph B["Blocking code"]
direction TB
b1["Request 1 arrives"] --> b2["Read file, thread waits"]
b2 --> b3["Request 1 is done"]
b3 --> b4["Request 2 can start only now"]
end
subgraph NB["Non-blocking code"]
direction TB
n1["Request 1 arrives"] --> n2["Start file read, move on"]
n2 --> n3["Request 2 starts right away"]
n3 --> n4["File is ready, callback runs"]
end
Express request life cycle
A request moves through middleware in the order you wrote them. Each one can pass the request on with next(), or stop and send a response. If something fails, the error goes to the error middleware.
flowchart TD req["Incoming request"] --> m1["Logger middleware"] m1 --> m2["express.json: reads the body"] m2 --> m3["Auth middleware: checks the token"] m3 -->|token is valid| r["Route handler: GET /api/users"] m3 -->|no token| e401["Send 401 response"] r -->|success| res["res.json: send response"] r -->|error| err["Error middleware: next(err)"] err --> res2["Send error response"]
Login with a JWT
The server checks the password once, then gives the user a signed token. After that, the user sends the token with each request. The server only needs to check the signature.
sequenceDiagram participant U as User browser participant S as Node API participant DB as Database U->>S: POST /login with email and password S->>DB: Find user by email DB-->>S: User with password hash S->>S: bcrypt.compare password with hash S-->>U: Signed JWT token U->>S: GET /profile with token in header S->>S: Verify token signature S-->>U: Profile data
Access token and refresh token
The access token is short-lived, so a stolen one stops working soon. The refresh token lives longer and is only used to get a new access token.
sequenceDiagram participant U as Client participant S as Server U->>S: Login S-->>U: Access token (15 min) and refresh token (7 days) U->>S: Request with access token S-->>U: 200 OK Note over U,S: 15 minutes later the access token expires U->>S: Request with expired access token S-->>U: 401 Unauthorized U->>S: Send refresh token S-->>U: New access token U->>S: Retry request with new token S-->>U: 200 OK
Streams and backpressure
Data moves in small chunks, so a huge file never has to fit in memory. When the writer is slower than the reader, it tells the reader to pause. This is called backpressure.
flowchart LR src["Readable: input file"] -->|chunk| tr["Transform: gzip"] tr -->|chunk| dst["Writable: output file"] dst -.->|buffer is full, slow down| tr tr -.->|pause reading| src
Cluster: one worker per CPU core
One Node.js process uses one CPU core. The cluster module starts many copies (workers) that share the same port. The primary process hands new connections to the workers.
flowchart TD
client["Clients"] --> lb["Primary process: shares the port"]
lb --> w1["Worker 1"]
lb --> w2["Worker 2"]
lb --> w3["Worker 3"]
lb --> w4["Worker 4"]
w1 --> db[("Database")]
w2 --> db
w3 --> db
w4 --> db
Which tool should I use for more CPU power?
Pick by the problem you have. Many requests need cluster. One heavy calculation needs a worker thread. Running another program needs a child process.
flowchart TD
q{"What do you need?"}
q -->|Use all CPU cores for a web server| c["cluster or PM2 cluster mode"]
q -->|Run a heavy JavaScript calculation| w["worker_threads"]
q -->|Run another program or script| p["child_process"]
Promise states
A promise starts as pending. It changes only once: to fulfilled when it works, or to rejected when it fails. After that it never changes again.
stateDiagram-v2 [*] --> Pending Pending --> Fulfilled: resolve is called Pending --> Rejected: reject is called or an error is thrown Fulfilled --> [*] Rejected --> [*]
What happens when you call require
Node.js loads each file only once. The second time you require the same file, you get the saved result from the cache.
flowchart TD
a["require('./utils')"] --> b{"Already in cache?"}
b -->|yes| c["Return cached exports"]
b -->|no| d["Find the file path"]
d --> e["Wrap the code in a function"]
e --> f["Run the code"]
f --> g["Save module.exports in cache"]
g --> c
A typical production setup
Users never talk to Node.js directly. A reverse proxy handles HTTPS and spreads traffic. Redis caches hot data. Slow jobs go to a queue and a background worker.
flowchart LR
user["Users"] --> proxy["HTTPS and Nginx reverse proxy"]
proxy --> n1["Node app instance 1"]
proxy --> n2["Node app instance 2"]
n1 --> redis[("Redis cache")]
n2 --> redis
n1 --> db[("Database")]
n2 --> db
n1 --> q["Job queue"]
q --> wk["Background worker"]
Graceful shutdown
When a server is asked to stop, it should not just die. It stops taking new requests, finishes the current ones, closes the database, and then exits.
sequenceDiagram participant P as Process manager participant N as Node app participant D as Database P->>N: SIGTERM signal N->>N: Stop accepting new connections N->>N: Finish running requests N->>D: Close connection N-->>P: process.exit 0
How a WebSocket connection starts
It starts as a normal HTTP request. The server agrees to switch protocols. After that the connection stays open and both sides can send messages at any time.
sequenceDiagram participant B as Browser participant S as Node server B->>S: HTTP request with Upgrade websocket S-->>B: 101 Switching Protocols Note over B,S: The connection stays open B->>S: Message from browser S->>B: Message pushed by server S->>B: Another message, any time
Your progress ticks are saved in this browser only.